CƯỜNG MÊ AI Học AI cùng Cường
CƯỜNG MÊ AI
Về mình Tài liệu
Học AI cùng Cường
Hướng dẫn từng bước · Claude · Mô hình 3D

Tạo video mô hình 3D bằng Claude, từ tiệm cà phê tới nhà máy

Claude viết trang web vẽ cảnh 3D, bạn quay màn hình thành video. Từ quán cà phê góc phố tới nhà máy nước tương tác.

Người mới làm được Claude + Three.js Đọc trong 25 phút · Tháng 11, 2026
canh-3d.html Claude · Three.js 1 Prompt gốc Khung 9:16, loop 10 giây 2 Phát lại Space, R hoặc click 3 Đổi chủ đề Thay chỗ trong ngoặc vuông 4 Sửa lỗi tải Bỏ import map 5 Zoom gần Lấy quán làm tâm 6 Cận cảnh Nhà búp bê, thấy barista 7 Xuyên mái Một cú máy 12 giây 8 Văn phòng Cùng kịch bản, đổi nơi chốn Cường Mê AI · Một prompt, một cảnh 3D

Tài liệu chia làm hai phần. Phần A là các cảnh 3D thu nhỏ, khung dọc 9:16, chuyển động lặp lại liền mạch, hợp làm video TikTok, Reels, Shorts. Phần B là mô hình nhà máy nước tương tác, khung ngang 16:9, có nút bấm, gây lỗi, dừng khẩn và tour 9 chương tự chạy. Hai phần dùng chung một cách làm: Viết yêu cầu cho Claude, Claude viết ra trang web, mình quay màn hình lại.

Đọc xong, anh em sẽ:

Mục lục
  1. Hiểu nhanh trước khi làm
  2. Phần A · Giải phẫu prompt gốc
  3. Phần A · Quy trình 8 bước, từ quán cà phê tới văn phòng
  4. Phần A · Quay và xuất video 9:16
  5. Phần B · Bản sao số là gì, mô hình có những gì
  6. Phần B · Cách mình làm mô hình nhà máy
  7. Phần B · Hướng dẫn dùng từng nút
  8. Phần B · Tour 9 chương và cách quay
  9. Phần B · Biến thành nhà máy của bạn
  10. Lỗi thường gặp
  11. Toàn bộ file mô hình và prompt

Hiểu nhanh trước khi làm

Anh em không cần biết code hay 3D. Nhưng nắm vài khái niệm dưới đây thì sẽ hiểu Claude đang làm gì và biết nhờ nó sửa đúng chỗ.

Cảnh này thực chất là một trang web

Claude không xuất ra file video. Nó viết một trang web (file .html), trong đó có đoạn code vẽ cảnh 3D lên màn hình 60 lần mỗi giây. Mở trang bằng trình duyệt là cảnh chạy. Muốn có video thì mình quay màn hình lại (cách quay ở phần 4).

Trên Claude, trang web này hiện ra dưới dạng artifact, hiểu nôm na là một trang Claude tạo ra và cho anh em mở xem ngay trong app, có đường link riêng, mặc định chỉ mình anh em xem được.

Mấy từ kỹ thuật trong prompt, nói cho dễ hiểu

Cần chuẩn bị
  1. Một tài khoản Claude (bản trả phí sẽ thoải mái hơn vì mỗi cảnh là một file code khá dài).
  2. Trình duyệt Chrome hoặc Edge trên máy tính. Điện thoại vẫn xem được nhưng quay video nên dùng máy tính.
  3. Một phần mềm quay màn hình: OBS Studio (miễn phí, Windows và macOS)[4], hoặc công cụ có sẵn: Win + G trên Windows, Cmd + Shift + 5 trên macOS.

Không cần cài Three.js hay bất cứ thư viện nào. Trang web tự tải khi mở.

Phần A

Cảnh 3D thu nhỏ cho video dọc

5 cảnh khung 9:16: Quán cà phê toàn cảnh, cận cảnh bên trong quán, xuyên mái vào quán, nhà máy AI và xuyên mái vào văn phòng.

Giải phẫu prompt gốc

Prompt viết bằng tiếng Anh vì Claude hiểu thuật ngữ 3D tiếng Anh chính xác hơn. Các chỗ trong ngoặc vuông [ ] là chỗ anh em thay theo ý mình. Phần còn lại là “khung kỹ thuật”, nên giữ nguyên để lần nào ra cảnh cũng đẹp và đồng bộ.

Prompt gửi Claude
Build a single-file web app (HTML, CSS, and JS) that plays a [10]-second looping 3D animation of [a busy corner coffee shop on a city block], made for a vertical 9:16 video.

Tech: Three.js from a CDN using an import map. RoundedBoxGeometry for every block, MeshStandardMaterial, one sun with soft shadows plus a hemisphere light, ACES tone mapping, and an ambient occlusion pass [GTAO].

World: a floating diorama on a rounded slab, packed with real, recognisable props built from simple shapes: [buildings with window grids, trees, cars, delivery scooters, people, street lamps]. Lots of small moving parts.

Motion: the world builds itself in the first second [pieces rise and pop with a little overshoot], then comes alive: [customers queue, scooters drive off, cars loop the block]. Camera: a slow ease orbit with a gentle push in, looping with no jump.

Style: clean isometric product render. Off-white ground, [royal blue, teal and green] with one bright orange accent. No textures, no 3D text.

Overlay: a frosted-glass card titled "[Daily Grind - Live Sales]" with three stats that tick up.

Frame: fill a 1088x1920 frame, no scrollbars, autoplay on load.

Từng dòng làm gì

Mẹo viết phần World và Motion

Hãy mô tả chuyển động như một dòng chảy có nhân quả thay vì liệt kê rời rạc. Ví dụ ở bản nhà máy AI: “cánh tay robot đặt chip lên băng chuyền → chip chạy vào data hall → tủ GPU sáng lên → drone chở hàng cất cánh”. Claude sẽ nối các chuyển động lại với nhau và số liệu trên thẻ cũng nhảy đúng lúc hành động xảy ra.

Lưu ý về lỗi chính tả

Bản prompt mình dùng lúc đầu có hai lỗi gõ: “cares alive” (đúng là comes alive) và “frosted-glass care” (đúng là card). Claude vẫn hiểu, nhưng bản ở phần 11 đã được sửa lại cho chuẩn.

Quy trình 8 bước, từ cảnh đầu tới bản văn phòng

Đây là đúng thứ tự mình đã làm trong một cuộc chat với Claude. Mỗi bước là một tin nhắn. Anh em có thể dừng ở bất kỳ bước nào nếu đã đủ dùng.

1

Dán prompt gốc, nhận cảnh đầu tiên

Mở một cuộc chat mới với Claude, dán nguyên prompt ở phần 2 rồi gửi. Claude sẽ viết code, chạy thử, rồi hiện ra một artifact. Bấm vào thẻ artifact để mở cảnh.

Kết quả: Khu phố có 3 tòa nhà (xanh royal, teal, xanh lá), quán cà phê góc phố với mái hiên sọc cam, hàng khách dịch lên mỗi 1,25 giây, 2 xe giao hàng rời quán chạy một vòng rồi quay về, xe hơi và xe buýt chạy quanh khối nhà. Thẻ “Daily Grind · Live Sales” có Orders, Revenue, Deliveries tự tăng, mỗi lần tăng số nháy màu cam.

2

Thêm nút phát lại để quay đoạn mở màn

Cảnh tự dựng chỉ xảy ra một lần lúc mới mở trang. Muốn quay lại đoạn mở màn mà không phải tải lại trang, nhắn:

Prompt gửi Claude
Thêm phím Space, phím R và click chuột để phát lại cảnh từ giây 0: dựng lại thế giới, chạy lại hiệu ứng thẻ, đưa số liệu về giá trị ban đầu.

Từ giờ, bấm quay phim trước, rồi nhấn Space là có đoạn mở màn sạch sẽ.

3

Đổi chủ đề: Chỉ thay phần trong ngoặc vuông

Khung prompt dùng lại được cho mọi bối cảnh. Mình đã thử đổi sang nhà máy AI bằng cách thay 5 chỗ: Chủ đề, danh sách đồ vật, chuỗi chuyển động, tên thẻ và 3 chỉ số. Prompt đầy đủ nằm ở phần 11.

Kết quả “NeuroForge”: Xưởng lắp ráp mái kính với 3 cánh tay robot (gắp chip, quét, hàn có tia lửa), băng chuyền đưa chip vào data hall, 15 tủ GPU sáng lên thành đợt mỗi khi nhận chip, tháp giải nhiệt bốc hơi, dàn pin mặt trời, drone giao hàng, xe tải tự lái có lidar quay, kỹ sư đội mũ bảo hộ cam.

Gợi ý bối cảnh để thử

Tiệm bánh mì sáng sớm, quán cà phê vỉa hè Sài Gòn với ghế nhựa và xe máy, chợ nổi, studio quay TikTok, nhà kho thương mại điện tử, bệnh viện, sân bay mini. Bối cảnh nào có “dòng người và dòng hàng” chạy qua lại thì càng hợp.

4

Sửa lỗi “không load được”

Bản nhà máy AI lúc đầu mở ra trắng tinh. Nguyên cớ thường gặp: Trình xem artifact có thể chèn script của nó trước import map (bảng chỉ đường cho trình duyệt biết lấy thư viện ở đâu), khiến trình duyệt bỏ qua bảng này và không tải được Three.js. Máy có card đồ họa yếu cũng có thể bị treo vì bóng đổ quá nét. Nhắn:

Prompt gửi Claude
Trang không load được. Đổi cách tải Three.js sang đường dẫn đầy đủ, không phụ thuộc import map. Giảm shadow map xuống 2048 và số mẫu GTAO xuống 12. Nếu cảnh không chạy được thì hiện một dòng báo lỗi ở cuối trang.

Sau khi sửa, nếu vẫn lỗi thì cuối trang sẽ hiện dòng “Không chạy được cảnh 3D: …”. Chụp dòng đó gửi Claude là nó biết sửa tiếp chỗ nào.

5

Zoom gần hơn, lấy quán làm tâm

Bản đầu đặt camera xa để thấy hết tấm đế. Với video ngắn, khán giả xem trên điện thoại, nhân vật chính cần to rõ hơn. Nhắn:

Prompt gửi Claude
Zoom camera vào gần khoảng gấp đôi, lấy quán cà phê làm tâm khung. Giữ chuyển động xoay chậm và đẩy vào nhẹ, lặp 10 giây không giật.

Khi zoom gần, phần trước tấm đế có thể bị “cắt cụt”. Đó là do mặt phẳng cắt gần của camera (camera không vẽ những gì quá sát nó). Claude đã tự chỉnh thông số này. Nếu anh em gặp, cứ nhắn “phía trước bị cắt mất, chỉnh near plane của camera”.

6

Cận cảnh bên trong quán

Muốn thấy barista và quầy pha chế, Claude làm kiểu nhà búp bê: Bỏ mái và hai bức tường phía trước để camera nhìn thẳng vào trong. Nhắn:

Prompt gửi Claude
Làm thêm một bản riêng: zoom hẳn vào bên trong quán để thấy barista và quầy pha chế. Cắt bỏ mái và hai bức tường phía trước như nhà búp bê. Mỗi 2,5 giây phục vụ xong một khách: gọi món, pha espresso, giao ly. Số Orders nhảy đúng lúc khách gọi món.

Kết quả: Máy espresso bốc hơi khi pha, tủ bánh kính, kệ hạt cà phê, bảng menu không chữ (chỉ vạch trắng và chấm giá cam), sàn gạch ca-rô, 3 khách ngồi bàn (2 người nhâm nhi, 1 người gõ laptop). Mỗi vòng 10 giây phục vụ đủ 4 khách.

7

Cảnh mở đầu: Một cú máy xuyên mái

Đây là bản đắt giá nhất để làm 3 giây đầu video. Nhắn:

Prompt gửi Claude
Làm cảnh mở đầu 12 giây, một cú máy liền mạch, không lặp: 0–4s toàn cảnh khu phố tự dựng lên; 4–6s camera lao xuống nóc quán; 6–7s mặt kính chìm xuống, tầng trên bật tung và bay vụt qua camera; 7–9s rơi vào trong và dừng ở cận cảnh barista đang pha cà phê. Sau đó camera đung đưa nhẹ để khung hình vẫn sống.

Mẹo nằm ở khoảnh khắc 6-7 giây: Tầng trên co lại một nhịp trước khi bật lên (giống lò xo nén). Chi tiết nhỏ này làm cú “xuyên mái” có lực hơn hẳn. Anh em muốn kịch tính hơn thì nhờ Claude tăng độ nén hoặc cho mái xoay nhiều vòng hơn.

8

Đổi sang bối cảnh văn phòng

Cùng kịch bản xuyên mái, chỉ đổi nơi chốn. Nhắn:

Prompt gửi Claude
Làm một bản tương tự nhưng là văn phòng: tòa nhà kính nhiều tầng, bên trong có cụm bàn làm việc, nhóm họp đứng ở bảng trắng, màn hình biểu đồ trên tường, góc pha cà phê. Thẻ số liệu gồm Tasks done, Closed today, Coffees, nhảy theo hành động trong cảnh.

Kết quả “Nimbus HQ”: 4 nhân viên gõ phím, ai xong việc thì màn hình sáng lên, huy hiệu tick xanh bay lên và người đó giơ tay. Nhóm họp đứng dán note cam vào cột “xong” rồi cả nhóm nhảy lên ăn mừng mỗi 5 giây, cột cam trên biểu đồ cao thêm và số “Closed today” tăng tiền. Góc pantry có người pha cà phê, cầm ly ra cửa sổ nhâm nhi rồi quay lại.

Vì sao số liệu “khớp” với hành động?

Mỗi chỉ số được gắn vào đúng thời điểm của một hành động trong cảnh: Khách gọi món thì Orders cộng 1, drone cất cánh thì Shipped cộng 1, cả nhóm ăn mừng thì Closed today tăng. Khi viết prompt, anh em nói rõ “số X nhảy khi Y xảy ra” là Claude sẽ nối hai thứ này lại. Video nhờ vậy có cảm giác “thật” hơn nhiều so với số chạy ngẫu nhiên.

Quay và xuất video 9:16

Trang web tự co khung 1088×1920 cho vừa cửa sổ trình duyệt. Để có video đẹp nhất:

1

Cho trình duyệt đúng kích thước

Mở cảnh bằng Chrome. Bấm F12 (macOS: Cmd + Option + I) để mở công cụ nhà phát triển, bấm biểu tượng điện thoại-máy tính bảng ở góc trên bên trái khung đó (Device Toolbar), chọn Responsive rồi gõ kích thước 1088 × 1920. Nếu màn hình nhỏ, chỉnh mức zoom của khung xem xuống 50%; tỉ lệ vẫn giữ đúng 9:16.

2

Bật quay, rồi mới phát lại

Mở OBS (hoặc Win + G / Cmd + Shift + 5), chọn vùng quay đúng khung hình. Bấm quay trước, sau đó click vào khung hoặc nhấn Space để cảnh dựng lại từ giây 0.

3

Quay đủ thời lượng, cắt phần thừa

  • Bản loop (quán cà phê, cận cảnh, nhà máy AI): Quay 0-10 giây nếu muốn có đoạn mở màn; muốn clip lặp liền mạch thì cắt bất kỳ đoạn 10 giây nào sau giây thứ 10 (vd 10-20).
  • Bản xuyên mái (quán cà phê, văn phòng): Quay 0-12 giây. Bản này không lặp, sau giây 8,8 camera ở lại trong nhà.

Cuối cùng cắt bỏ đoạn đầu clip (trước lúc nhấn Space) trong CapCut hoặc Premiere.

Số trên thẻ không lặp

Chuyển động trong cảnh lặp đúng 10 giây, nhưng các con số trên thẻ thì tăng liên tục. Nếu cần ghép vòng lặp nhiều lần, hãy cắt sao cho người xem không để ý số bị “nhảy lùi”, hoặc nhờ Claude cho số reset theo chu kỳ.

Muốn file MP4 khỏi phải quay màn hình

Các bản xuyên mái có sẵn chế độ “đóng băng thời gian” để render từng khung chính xác. Anh em có thể nhờ Claude: “Xuất cảnh này ra MP4 1088×1920, 30fps, dài 12 giây”. Claude sẽ chạy trình duyệt ẩn, chụp từng khung rồi ghép thành video. Cách này lâu hơn quay màn hình nhưng không bao giờ giật hay lệch khung.

Phần B

Nhà máy nước tương tác

Bản sao số dây chuyền chiết rót nước 1,5L, khung 16:9: Bấm vào máy, bấm vào chai, gây lỗi, dừng khẩn và tour 9 chương tự chạy.

Bản sao số là gì, mô hình có những gì

Toàn cảnh mô hình nhà máy nước
Toàn cảnh mô hình: Từ bồn xử lý nước bên trái tới robot xếp pallet và kho bên phải.

Bản sao số (tiếng Anh: Digital twin) là một bản mô phỏng trên máy tính của một thứ có thật: Nhà máy, máy móc, tòa nhà. Bản sao chạy song song với đời thật, nhìn vào là biết máy nào đang chạy, chỗ nào đang lỗi, sản lượng bao nhiêu.[5] Ngoài đời, các nhà máy lớn trả rất nhiều tiền cho hệ thống kiểu này. Ở đây, mô hình chạy bằng số liệu mẫu, nhưng giao diện và cách tương tác giống y một hệ thống thật.

Dây chuyền trong mô hình, theo thứ tự chai đi qua

  1. Xử lý nước: 3 bồn inox và cụm lọc, đường ống dẫn nước sang máy chiết.
  2. Máy thổi chai: Bánh khuôn quay bên trong, phôi nhựa được thổi thành chai 1,5L.
  3. Chiết rót và đóng nắp 3 trong 1: Mâm quay có đúng 60 van chiết; van hạ xuống khi chai đi tới, nước dâng dần trong từng chai. Kế bên là cụm 18 đầu đóng nắp và phễu cấp nắp xanh.
  4. Soi đèn và loại lỗi: Tấm đèn sau lưng chai, camera trước mặt, cần đẩy màu đỏ gạt chai lỗi ra bàn loại.
  5. Dán nhãn và hầm co: Cuộn nhãn quay, chai ra khỏi máy có nhãn xanh.
  6. Màng co thành lốc: Gom 12 chai thành 1 lốc, đi qua hầm nhiệt có ánh cam.
  7. Robot xếp pallet: Robot 6 trục màu cam gắp từng lốc, xếp 9 lốc một lớp, 4 lớp một pallet.
  8. Kho thành phẩm: Kệ chứa nhiều tầng và xe nâng chạy qua lại.

Xung quanh còn có phòng điều khiển trên gác lửng, cầu thang vàng bắc qua băng tải, tủ điện, lối đi xanh và công nhân đội mũ bảo hộ đi lại.

Vì sao mọi thứ chạy “khớp” với nhau?

Cả dây chuyền dùng chung một chiếc đồng hồ. Chai, van chiết, đầu đóng nắp, lốc hàng và robot đều tính vị trí theo đồng hồ đó. Khi dây chuyền giảm tốc hay dừng khẩn, chỉ cần đồng hồ chạy chậm lại là tất cả cùng chậm theo, không có máy nào chạy lệch nhịp. Đây là ý tưởng quan trọng nhất nếu anh em muốn tự làm mô hình tương tự.

Cách mình làm mô hình với Claude

Phần dưới đây là các bước mình đã làm cùng Claude, kèm những gì Claude làm phía sau, để anh em hiểu và biết cách ra lệnh cho sát ý.

1

Mô tả nhà máy muốn có

Mở một cuộc chat mới với Claude và mô tả đủ 4 thứ: Dây chuyền gồm những máy nào theo thứ tự, chuyển động (chai chạy, van chiết, robot), tương tác (bấm máy, truy vết chai, gây lỗi, dừng khẩn) và giao diện (thanh tab, ô OEE, bảng thông số, tour tự chạy). Bản tóm tắt bằng tiếng Việt:

Prompt gửi Claude
Dựng một trang web 3D mô phỏng dây chuyền chiết rót nước 1,5L trong nhà xưởng: xử lý nước, thổi chai, chiết rót 60 van và đóng nắp 18 đầu, soi đèn loại lỗi, dán nhãn, màng co lốc 12 chai, robot xếp pallet, kho. Bấm vào máy để xem thông số, bấm vào chai để camera bám theo, có nút tách lớp, gây thiếu nắp, lỗi van, dừng khẩn và tour 9 chương để quay video. Giao diện tiếng Việt, khung 16:9.

Bản đầy đủ, chi tiết từng máy và từng nút, nằm trong ô 01-prompt-dung-nha-may.txt ở phần 11. Dán nguyên văn là ra mô hình tương tự.

2

Chốt bố cục và 9 chương tour

Trước khi viết code, Claude sắp xếp các máy theo đúng thứ tự chai đi qua, chọn vị trí phòng điều khiển, kho, lối đi, rồi lên nội dung 9 chương tour: Mỗi chương một tính năng, có tiêu đề và dòng mô tả để làm phụ đề cho video.

3

Vẽ đường đi của chai trước, đặt máy sau

Đây là mẹo hay. Thay vì đặt máy rồi nối băng tải, Claude vẽ trước đường đi của chai: Đi thẳng từ máy thổi, vòng nửa vòng quanh mâm chiết, vòng ngược quanh mâm đóng nắp, rồi đi thẳng tới máy màng co. Sau đó mới đặt từng máy đúng vào tâm các vòng cung. Nhờ vậy chai luôn nằm đúng dưới van chiết, đúng dưới đầu đóng nắp, không bao giờ lệch.

Khoảng cách giữa hai chai được chọn để vòng 60 van vừa khít: Mỗi van ứng với đúng một chai. Đó là lý do van chiết “đi theo” chai một cách tự nhiên.

4

Dựng giao diện điều khiển tiếng Việt

Thanh trên cùng có tab từng khu vực, trạng thái chạy và đồng hồ. Góc trái là ô OEE (chỉ số hiệu quả thiết bị tổng thể, càng gần 100% càng tốt) và sản lượng thực. Bên phải là bảng thông số. Góc trái dưới là bản đồ nhỏ, dưới cùng là thanh nút điều khiển, giữa là hộp phụ đề nền tối viền cam để hiện tiêu đề từng chương khi chạy tour.

5

Tự chạy thử, chụp lại, sửa rồi mới giao

Claude mở mô hình bằng một trình duyệt ẩn, chụp màn hình từng chế độ (toàn cảnh, tách lớp, truy vết chai, loại chai lỗi, dừng khẩn, robot) và cả 9 chương tour. Lần chạy thử đầu tiên phát hiện vài lỗi nhỏ: Camera máy chiết đặt quá gần, thanh nút bị tràn ở màn hình 1280px, một công nhân đứng chắn camera trạm soi đèn. Claude sửa hết rồi mới gửi.

Mẹo ra lệnh cho sát ý

Nêu con số cụ thể ngay trong yêu cầu: 60 van chiết, 18 đầu đóng nắp, 12 chai một lốc, 9 lốc một lớp, dừng trong 0,6 giây. Con số càng rõ, Claude dựng càng đúng và các chi tiết khớp nhau hơn, không phải sửa đi sửa lại.

Hướng dẫn dùng từng nút

Di chuyển camera

Xem máy và truy vết chai

Truy vết một chai
Truy vết một chai: Camera bám theo, bảng bên phải ghi giờ chai qua từng công đoạn.

Các nút trên thanh điều khiển

NútTác dụng
Chạy tourTự chạy 9 chương có phụ đề. Bấm lần nữa để dừng.
Tạm dừng · 1× 2× 4×Đóng băng cả dây chuyền, hoặc tua nhanh gấp 2, gấp 4.
Truy vết chaiChọn một chai đang ở máy chiết và bám theo nó.
Xuyên thấuLàm mái các buồng máy trong suốt để nhìn vào bên trong.
Tách lớpKéo thanh trượt: Bồn chứa, vòng 60 van, 18 đầu đóng nắp tách lên theo từng tầng, vách kính lùi ra xa.
Gây thiếu nắpChai kế tiếp qua máy đóng nắp sẽ không có nắp. Khi tới trạm soi: Đèn chuyển đỏ, hiện chữ NG, cần đẩy gạt chai ra bàn loại, ô “Đã loại” tăng 1.
Lỗi van chiếtVan số 24 chuyển đỏ, cả dây chuyền giảm còn 60%, sản lượng và OEE giảm theo. Bấm lần nữa để xử lý xong.
Dừng khẩnToàn tuyến dừng trong 0,6 giây, đèn tháp đỏ nhấp nháy. Bấm “Khởi động lại” để tăng tốc về định mức trong 2,5 giây.
Đặt lạiTắt mọi sự cố, đưa camera về toàn cảnh.

Phím tắt: T Chạy hoặc dừng tour, Space tạm dừng mô phỏng, Esc thoát tour.

Tách lớp máy chiết rót
Tách lớp máy chiết rót: Bồn chứa, vòng 60 van và cụm 18 đầu đóng nắp tách lên theo từng tầng.
Loại chai thiếu nắp
Gây thiếu nắp: Trạm soi đèn báo NG, chai bị gạt ra bàn loại màu cam, ô “Đã loại” tăng lên.

Tour 9 chương và cách quay video

Bấm Chạy tour là mô hình tự diễn trọn 9 chương, khoảng 82 giây. Các sự cố được kích hoạt đúng lúc, không cần bấm gì thêm.

MốcTiêu đề trên màn hìnhChuyện gì xảy ra
0:00Nhà máy này là một trang web.Toàn cảnh xưởng, camera xoay chậm.
0:08Bấm máy nào, xem máy đó.Bay tới máy chiết rót rồi trạm soi đèn, bảng thông số đổi theo.
0:16Tách máy chiết rót thành từng lớp.Máy chiết tách ra từng tầng rồi ghép lại.
0:25Bấm một chai, camera bám theo.Bám một chai từ máy chiết tới máy dán nhãn.
0:36Thiếu nắp, loại ngay tại chỗ.Chai thiếu nắp bị phát hiện và gạt ra.
0:46Một van báo động, cả dây chuyền giảm tốc.Van #24 đỏ, tốc độ còn 60%, rồi hồi phục.
0:56Một nút dừng khẩn, cả tuyến đứng yên.Dừng 0,6 giây, khởi động lại sau 4 giây.
1:05Robot xếp pallet theo nhịp.Robot gắp và xếp lốc lên pallet.
1:14Từ một câu yêu cầu, tới cả một nhà máy.Kéo ra toàn cảnh, kết thúc ở 1:22.

Ô 03-kich-ban-tour-9-chuong.txt ở phần 11 có sẵn lời lồng tiếng gợi ý cho từng chương.

1

Mở toàn màn hình

Mở file mô hình bằng Chrome, nhấn F11 (macOS: Cmd + Ctrl + F) cho toàn màn hình. Màn hình 1920×1080 cho ra video 16:9 nét nhất.

2

Bật quay rồi mới chạy tour

Mở OBS, chọn nguồn quay là cửa sổ Chrome. Bấm quay trước, sau đó nhấn T để bắt đầu tour. Đợi hết 9 chương (phụ đề tự trở về dòng hướng dẫn ban đầu) rồi dừng quay.

3

Cắt ghép và lồng tiếng

Đưa vào CapCut hoặc Premiere, cắt bỏ đoạn đầu trước khi nhấn T. Thanh cam mảnh ở đáy hộp phụ đề chạy hết là hết chương, dùng làm mốc cắt rất tiện.

Muốn làm video dọc cho TikTok

Mô hình được thiết kế cho khung ngang 16:9. Để có bản dọc 9:16 đẹp, hãy gửi Claude file mô hình kèm câu lệnh “Làm thêm bản dọc 9:16” trong file 02-lenh-chinh-sua.txt. Claude sẽ sắp xếp lại giao diện cho khung dọc thay vì chỉ cắt hai bên.

Biến thành nhà máy của bạn

Cách nhanh nhất: Kéo-thả file nha-may-nuoc.html vào khung chat Claude, rồi gửi kèm một câu lệnh. Vài ví dụ:

Prompt gửi Claude
Đổi dây chuyền thành sữa hộp giấy: thay hình dáng sản phẩm, thay máy chiết bằng máy phù hợp, giữ nguyên toàn bộ tương tác.
Prompt gửi Claude
Đổi tên nhà máy thành "Cường Mê AI Factory", đổi màu chính sang tím, viết lại phụ đề 9 chương theo giọng hài hước.
Prompt gửi Claude
Thêm nút "Kẹt chai ở băng tải": chai dồn ứ trước máy dán nhãn, cảm biến báo vàng, dây chuyền tự giảm tốc rồi hồi phục.

Muốn dựng từ đầu một nhà máy khác, dùng prompt đầy đủ trong file 01-prompt-dung-nha-may.txt và thay các phần trong ngoặc vuông.

Robot xếp pallet
Robot xếp pallet: Bảng bên phải hiện chu kỳ, lớp hiện tại và số lốc trên pallet.

Lỗi thường gặp và cách sửa

Trang trắng, không thấy gì

Cảnh chạy giật, quạt máy kêu to

Đồ vật bị cắt cụt khi camera lại gần

Nhắn: “Phía trước bị cắt mất khi zoom gần, chỉnh near plane của camera nhỏ lại.”

Có vật che mất góc nhìn

Ở bản cận cảnh, bộ bàn ghế có dù cam ngoài vỉa hè che tầm nhìn vào quán nên mình đã bỏ đi. Cứ chụp màn hình, khoanh chỗ bị che rồi nhờ Claude “bỏ hoặc dời vật này”.

Đừng sửa tay một file quá dài

Mỗi file cảnh dài khoảng 800-1.100 dòng code. Nếu muốn đổi màu, đổi tên thương hiệu hay chỉ số, hãy nhờ Claude sửa thay vì tự sửa tay. Một dấu ngoặc sai là cả cảnh không chạy.

Camera bị kẹt hoặc lạc hướng

Bấm tab Tổng quan hoặc nút Đặt lại. Khi đang truy vết chai, mọi thao tác kéo chuột vẫn xoay quanh chai đó; bấm lại “Truy vết chai” để thoát.

Số liệu là số mẫu

Tên nhà máy, công suất, nhiệt độ, áp suất, OEE... đều là số mẫu để minh họa. Nếu dùng làm nội dung giới thiệu cho khách hàng thật, hãy nhờ Claude thay bằng thông số thật của dây chuyền đó.

Toàn bộ file mô hình và prompt để copy

Mỗi ô dưới đây là một file hoàn chỉnh. Bấm Copy, dán vào Notepad hay trình soạn thảo bất kỳ, lưu với đuôi .html (mô hình) hoặc .txt (prompt). File .html nhấp đúp là mở bằng trình duyệt, cần internet.

Cách dùng các file này Dễ nhất
  1. Xem ngay: Copy một file mô hình, dán vào Notepad, lưu với đuôi .html, rồi nhấp đúp. Trình duyệt mở lên là chạy.
  2. Chỉnh thành của mình: Đính kèm file .html đã lưu vào khung chat Claude, rồi nhắn điều muốn đổi, ví dụ: “Đổi tên thành Cường Mê AI Studio, chuyển số liệu sang tiếng Việt, đổi màu nhấn sang tím”. Claude sửa và trả lại bản mới.
  3. Làm cảnh mới: Mở ô prompt khung (phần A) hoặc prompt dựng nhà máy (phần B), thay các chỗ trong ngoặc vuông, dán vào Claude.

5 cảnh 3D cho video dọc

Quán cà phê toàn cảnh, cận cảnh bên trong quán, xuyên mái vào quán cà phê, nhà máy AI NeuroForge, xuyên mái vào văn phòng Nimbus HQ. Nhấn Space, R hoặc click để phát lại từ giây 0.

canh-3d-video-doc/01-quan-ca-phe-toan-canh.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
</head>
<body>
<title>Daily Grind Diorama</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,800&family=Manrope:wght@500;600;700;800&display=swap">
<style>
/* Layout: fixed 1088x1920 frame scaled to fit the window; frosted card floats over the top third, diorama sits low. */
:root{
  --bg:#e9ecf1;
  --frame:#f6f7f9;
  --ink:#141b38;
  --muted:#5a6383;
  --accent:#ff7a1c;
  --royal:#2f55e6;
  --teal:#17a99c;
  --green:#3db86a;
  --f-display:'Bricolage Grotesque','Manrope',system-ui,sans-serif;
  --f-body:'Manrope',system-ui,-apple-system,'Segoe UI',sans-serif;
  color-scheme:light;
}
html,body{height:100%;margin:0;overflow:hidden;background:var(--bg);color:var(--ink)}
#stage{
  position:absolute;left:50%;top:50%;
  width:1088px;height:1920px;
  transform:translate(-50%,-50%) scale(var(--s,0.4));
  transform-origin:center center;
  overflow:hidden;background:var(--frame);
}
#c{position:absolute;inset:0;display:block;width:1088px;height:1920px}
.vignette{position:absolute;inset:0;pointer-events:none;
  background:radial-gradient(120% 80% at 50% 60%, rgba(255,255,255,0) 55%, rgba(20,27,56,.07) 100%)}

.card{
  position:absolute;left:84px;right:84px;top:132px;
  padding:42px 48px 44px;
  border-radius:44px;
  background:linear-gradient(160deg, rgba(255,255,255,.62), rgba(255,255,255,.34));
  -webkit-backdrop-filter:blur(26px) saturate(1.5);
  backdrop-filter:blur(26px) saturate(1.5);
  border:1.5px solid rgba(255,255,255,.85);
  box-shadow:0 30px 80px -30px rgba(20,27,56,.35), inset 0 1px 0 rgba(255,255,255,.9);
  font-family:var(--f-body);
  opacity:0;transform:translateY(-24px) scale(.98);
  animation:cardIn .7s cubic-bezier(.2,.9,.25,1.15) .55s forwards;
}
@keyframes cardIn{to{opacity:1;transform:none}}
.head{display:flex;align-items:center;justify-content:space-between;gap:24px}
.brand{display:flex;align-items:center;gap:22px}
.mark{width:68px;height:68px;border-radius:22px;background:var(--accent);position:relative;
  box-shadow:0 10px 24px -8px rgba(255,122,28,.7)}
.mark::before{content:"";position:absolute;left:18px;top:22px;width:26px;height:28px;border-radius:5px 5px 10px 10px;background:#fff}
.mark::after{content:"";position:absolute;left:42px;top:27px;width:9px;height:13px;border:4px solid #fff;border-left:0;border-radius:0 8px 8px 0}
h1{margin:0;font-family:var(--f-display);font-weight:800;font-size:56px;line-height:1;letter-spacing:-.02em;text-wrap:balance}
h1 span{color:var(--muted);font-weight:600}
.sub{margin:10px 0 0;font-size:22px;font-weight:600;color:var(--muted);letter-spacing:.01em}
.live{display:flex;align-items:center;gap:12px;padding:12px 20px;border-radius:999px;
  background:rgba(20,27,56,.9);color:#fff;font-weight:800;font-size:20px;letter-spacing:.16em}
.live i{width:14px;height:14px;border-radius:50%;background:var(--accent);box-shadow:0 0 0 0 rgba(255,122,28,.7);animation:pulse 1s ease-out infinite}
@keyframes pulse{0%{box-shadow:0 0 0 0 rgba(255,122,28,.75)}100%{box-shadow:0 0 0 16px rgba(255,122,28,0)}}
.stats{display:grid;grid-template-columns:1fr 1.25fr 1fr;gap:0;margin-top:36px;
  border-top:1.5px solid rgba(20,27,56,.09)}
.stat{padding:30px 0 0 28px;display:flex;flex-direction:column;gap:10px;min-width:0;border-left:1.5px solid rgba(20,27,56,.09)}
.stat:first-child{padding-left:0;border-left:0}
.label{font-size:19px;font-weight:800;text-transform:uppercase;letter-spacing:.14em;color:var(--muted);display:flex;align-items:center;gap:10px}
.label b{width:12px;height:12px;border-radius:4px;display:inline-block}
.val{font-family:var(--f-body);font-weight:800;font-size:66px;line-height:1;letter-spacing:-.03em;
  font-variant-numeric:tabular-nums;color:var(--ink);display:inline-block;transform-origin:left bottom}
.val.bump{animation:bump .55s ease-out}
@keyframes bump{0%{color:var(--accent);transform:translateY(-6px) scale(1.04)}100%{color:var(--ink);transform:none}}
.delta{font-size:20px;font-weight:700;color:var(--teal);font-variant-numeric:tabular-nums}
@media (prefers-reduced-motion: reduce){.card{animation-duration:.01s}.live i{animation:none}}
</style>

<div id="stage">
  <canvas id="c" width="1088" height="1920"></canvas>
  <div class="vignette"></div>
  <section class="card" aria-label="Daily Grind live sales">
    <div class="head">
      <div class="brand">
        <div class="mark" aria-hidden="true"></div>
        <div>
          <h1>Daily Grind <span>· Live Sales</span></h1>
          <p class="sub">5th &amp; Pine corner store · today</p>
        </div>
      </div>
      <div class="live"><i></i>LIVE</div>
    </div>
    <div class="stats">
      <div class="stat">
        <span class="label"><b style="background:var(--royal)"></b>Orders</span>
        <span class="val" id="sOrders">1,284</span>
        <span class="delta" id="dOrders">+48 / hr</span>
      </div>
      <div class="stat">
        <span class="label"><b style="background:var(--accent)"></b>Revenue</span>
        <span class="val" id="sRev">$6,842</span>
        <span class="delta" id="dRev">avg ticket $6.10</span>
      </div>
      <div class="stat">
        <span class="label"><b style="background:var(--green)"></b>Deliveries</span>
        <span class="val" id="sDel">212</span>
        <span class="delta">2 riders out</span>
      </div>
    </div>
  </section>
</div>

<div id="err" hidden style="position:fixed;left:16px;right:16px;bottom:16px;padding:14px 16px;border-radius:12px;background:#141b38;color:#fff;font:600 14px/1.4 Manrope,system-ui,sans-serif;z-index:9"></div>
<script>
(function(){
  var el=document.getElementById('err');
  function show(m){ el.hidden=false; el.textContent='Không chạy được cảnh 3D: '+m; }
  window.addEventListener('error',function(e){ show(e.message||'lỗi tải script'); },true);
  window.addEventListener('unhandledrejection',function(e){ show(String(e.reason&&e.reason.message||e.reason)); });
  setTimeout(function(){ if(!window.__sceneOK) show('thư viện Three.js chưa tải xong sau 15 giây (mạng hoặc CDN bị chặn).'); },15000);
})();
</script>
<script type="importmap">
{ "imports": {
  "three": "https://cdn.jsdelivr.net/npm/three@0.160.0/+esm"
} }
</script>

<script type="module">
import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.160.0/+esm';
import { RoundedBoxGeometry } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/geometries/RoundedBoxGeometry.js/+esm';
import { EffectComposer } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/EffectComposer.js/+esm';
import { RenderPass } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/RenderPass.js/+esm';
import { GTAOPass } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/GTAOPass.js/+esm';
import { OutputPass } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/OutputPass.js/+esm';

const W = 1088, H = 1920, LOOP = 10, TAU = Math.PI * 2;

/* ---------- fit frame to window ---------- */
const stage = document.getElementById('stage');
function fit(){ stage.style.setProperty('--s', Math.min(innerWidth / W, innerHeight / H)); }
addEventListener('resize', fit); fit();

/* ---------- palette ---------- */
const C = {
  ground:0xf7f6f2, base:0x2a48d4, road:0xd2d7e0, walk:0xe6e9ee, line:0xffffff,
  royal:0x2f55e6, royalDeep:0x2340b8, teal:0x17a99c, tealLight:0x93e0d6,
  green:0x3db86a, greenDeep:0x22864a, greenLight:0x92dba6,
  orange:0xff7a1c, white:0xffffff, navy:0x1d2547, tire:0x2b3040, glass:0xcdeef4,
  trunk:0x8d847b, stone:0xc9ced8,
  skin:[0xf2cba8,0xdba57e,0xae7652,0x7d5136], hair:[0x2b2420,0x5a3b25,0x1d2547,0xd9b77a]
};

/* ---------- seeded random ---------- */
function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296}}
const rnd = mulberry32(11);
const pick = arr => arr[Math.floor(rnd() * arr.length)];
const clamp01 = x => Math.min(1, Math.max(0, x));
const smooth = x => { x = clamp01(x); return x * x * (3 - 2 * x); };
const easeOutCubic = x => 1 - Math.pow(1 - x, 3);
const easeOutBack = x => { const c1 = 2.1, c3 = c1 + 1; return 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2); };

/* ---------- renderer ---------- */
const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('c'), antialias: true, powerPreference: 'high-performance' });
renderer.setPixelRatio(1);
renderer.setSize(W, H, false);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;

const scene = new THREE.Scene();
scene.background = new THREE.Color(0xf7f8fa);

const camera = new THREE.PerspectiveCamera(32, W / H, 20, 200);
camera.setViewOffset(W, H, 0, -320, W, H); // drop the diorama below the card

/* ---------- lights ---------- */
scene.add(new THREE.HemisphereLight(0xeef3ff, 0xd8d3c8, 1.35));
const sun = new THREE.DirectionalLight(0xfff4e6, 2.7);
sun.position.set(-12, 26, 14);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
Object.assign(sun.shadow.camera, { left:-20, right:20, top:20, bottom:-20, near:1, far:80 });
sun.shadow.bias = -0.0004;
sun.shadow.normalBias = 0.025;
sun.shadow.radius = 5;
scene.add(sun);

/* ---------- geometry + material helpers ---------- */
const geoCache = new Map(), matCache = new Map();
function geo(w, h, d, r){
  r = r ?? Math.min(0.14, Math.min(w, h, d) * 0.22);
  r = Math.min(r, Math.min(w, h, d) / 2 - 0.001);
  const k = [w, h, d, r].map(v => v.toFixed(3)).join('|');
  if (!geoCache.has(k)) geoCache.set(k, new RoundedBoxGeometry(w, h, d, 2, r));
  return geoCache.get(k);
}
function mat(color, o = {}){
  const k = [color, o.rough, o.metal, o.emissive, o.ei, o.opacity].join('|');
  if (!matCache.has(k)) matCache.set(k, new THREE.MeshStandardMaterial({
    color, roughness: o.rough ?? 0.62, metalness: o.metal ?? 0,
    emissive: o.emissive ?? 0x000000, emissiveIntensity: o.ei ?? 1,
    transparent: o.opacity !== undefined, opacity: o.opacity ?? 1
  }));
  return matCache.get(k);
}
function box(parent, w, h, d, color, x = 0, y = 0, z = 0, o = {}){
  const m = new THREE.Mesh(geo(w, h, d, o.r), o.material || mat(color, o));
  m.position.set(x, y, z);
  m.castShadow = o.cast !== false;
  m.receiveShadow = true;
  parent.add(m);
  return m;
}
// bottom-aligned box
const boxB = (p, w, h, d, c, x, y, z, o) => box(p, w, h, d, c, x, y + h / 2, z, o);

/* ---------- build-in system ---------- */
const builds = [];
function prop(x, y, z, delay){
  const root = new THREE.Group(); root.position.set(x, y, z);
  const inner = new THREE.Group(); root.add(inner);
  scene.add(root);
  const dist = Math.hypot(x, z);
  builds.push({ inner, delay: delay ?? (0.16 + (dist / 18) * 0.5 + rnd() * 0.12) });
  return { root, inner };
}
let buildDone = false;
function applyBuild(t){
  if (buildDone) return;
  let all = true;
  for (const b of builds){
    const x = clamp01((t - b.delay) / 0.42);
    if (x < 1) all = false;
    b.inner.visible = x > 0;
    b.inner.scale.setScalar(Math.max(0.001, easeOutBack(x)));
    b.inner.position.y = -1.6 * (1 - easeOutCubic(x));
  }
  if (all) buildDone = true;
}

/* ---------- lane path: rounded rectangle, arc-length param ---------- */
function makePath(h, rc){
  const a = 2 * (h - rc), arc = Math.PI * rc / 2, L = 4 * a + 4 * arc, k = h - rc;
  const starts = [[-k, h], [h, k], [k, -h], [-h, -k]];
  const dirs = [[1, 0], [0, -1], [-1, 0], [0, 1]];
  const centers = [[k, k], [k, -k], [-k, -k], [-k, k]];
  const th0 = [Math.PI / 2, 0, -Math.PI / 2, -Math.PI];
  return { L, at(s, rev){
    if (rev) s = L - s;
    s = ((s % L) + L) % L;
    const seg = a + arc, i = Math.min(3, Math.floor(s / seg)), r = s - i * seg;
    let x, z, dx, dz;
    if (r < a){ x = starts[i][0] + dirs[i][0] * r; z = starts[i][1] + dirs[i][1] * r; dx = dirs[i][0]; dz = dirs[i][1]; }
    else { const th = th0[i] - (r - a) / rc; x = centers[i][0] + rc * Math.cos(th); z = centers[i][1] + rc * Math.sin(th); dx = Math.sin(th); dz = -Math.cos(th); }
    if (rev){ dx = -dx; dz = -dz; }
    return { x, z, yaw: Math.atan2(-dz, dx) };
  } };
}

/* ======================================================================
   WORLD
   ====================================================================== */
const ROAD_IN = 6.4, ROAD_OUT = 10.6, BY = 0.22, RY = 0.06;

// slab
{
  const p = prop(0, 0, 0, 0);
  box(p.inner, 26, 1.0, 26, C.ground, 0, -0.5, 0, { r: 0.45 });
  box(p.inner, 25.2, 0.42, 25.2, C.base, 0, -1.12, 0, { r: 0.2, cast: false });
}
// road + markings
{
  const p = prop(0, 0, 0, 0.06);
  box(p.inner, ROAD_OUT * 2, RY, ROAD_OUT * 2, C.road, 0, RY / 2, 0, { r: 0.03, cast: false });
  const h = 8.65, rc = 1.4;
  for (let side = 0; side < 4; side++){
    for (let u = -h + rc + 0.7; u < h - rc - 0.5; u += 1.3){
      const m = box(p.inner, 0.62, 0.02, 0.1, C.line, 0, RY + 0.01, 0, { r: 0.009, cast: false });
      if (side === 0) m.position.set(u, m.position.y, h);
      if (side === 1) { m.position.set(h, m.position.y, u); m.rotation.y = Math.PI / 2; }
      if (side === 2) m.position.set(u, m.position.y, -h);
      if (side === 3) { m.position.set(-h, m.position.y, u); m.rotation.y = Math.PI / 2; }
    }
  }
  // teal bike-lane line
  const bl = 7.3;
  for (const s of [1, -1]){
    box(p.inner, bl * 2 - 1.6, 0.02, 0.07, C.teal, 0, RY + 0.01, s * bl, { r: 0.009, cast: false });
    box(p.inner, 0.07, 0.02, bl * 2 - 1.6, C.teal, s * bl, RY + 0.01, 0, { r: 0.009, cast: false });
  }
  // crosswalks
  for (let z = ROAD_IN + 0.35; z < ROAD_OUT - 0.2; z += 0.62) box(p.inner, 1.4, 0.02, 0.32, C.line, -0.6, RY + 0.012, z, { r: 0.009, cast: false });
  for (let x = ROAD_IN + 0.35; x < ROAD_OUT - 0.2; x += 0.62) box(p.inner, 0.32, 0.02, 1.4, C.line, x, RY + 0.012, -0.6, { r: 0.009, cast: false });
}
// block sidewalk
{
  const p = prop(0, 0, 0, 0.1);
  box(p.inner, ROAD_IN * 2, BY, ROAD_IN * 2, C.walk, 0, BY / 2, 0, { r: 0.08 });
}

/* ---------- window grids (instanced) ---------- */
const _m = new THREE.Matrix4(), _q = new THREE.Quaternion(), _s = new THREE.Vector3(1, 1, 1), _v = new THREE.Vector3();
function windows(parent, { w, d, y0, floors, fh, cols, colsSide, ww = 0.5, wh = 0.62, color = C.glass }){
  const list = [];
  for (let f = 0; f < floors; f++){
    const y = y0 + f * fh;
    for (let c = 0; c < cols; c++) list.push([(c - (cols - 1) / 2) * (w / cols), y, d / 2, 0]);
    for (let c = 0; c < colsSide; c++) list.push([w / 2, y, (c - (colsSide - 1) / 2) * (d / colsSide), Math.PI / 2]);
  }
  const im = new THREE.InstancedMesh(geo(ww, wh, 0.1, 0.035), mat(color, { rough: 0.18, metal: 0.15 }), list.length);
  list.forEach(([x, y, z, ry], i) => {
    _q.setFromAxisAngle(_v.set(0, 1, 0), ry);
    _m.compose(new THREE.Vector3(x, y, z), _q, _s);
    im.setMatrixAt(i, _m);
  });
  im.castShadow = true; im.receiveShadow = true;
  parent.add(im);
  return im;
}

const fans = [], blinkers = [];
function building({ x, z, w, d, h, color, trim, cols, colsSide }){
  const p = prop(x, BY, z);
  const g = p.inner;
  boxB(g, w, h, d, color, 0, 0, 0, { r: 0.14 });
  boxB(g, w + 0.14, 0.18, d + 0.14, trim, 0, h, 0, { r: 0.06 });
  // storefront band
  boxB(g, w * 0.86, 0.72, 0.1, C.glass, 0, 0.18, d / 2, { r: 0.04, rough: 0.2 });
  boxB(g, 0.1, 0.72, d * 0.86, C.glass, w / 2, 0.18, 0, { r: 0.04, rough: 0.2 });
  boxB(g, w + 0.06, 0.12, d + 0.06, trim, 0, 1.05, 0, { r: 0.04 });
  const fh = 1.05, floors = Math.floor((h - 1.6) / fh);
  windows(g, { w, d, y0: 1.75, floors, fh, cols, colsSide });
  return { p, g, h };
}

// Tower (royal blue)
{
  const b = building({ x: -3.0, z: -3.0, w: 5.0, d: 5.0, h: 9.6, color: C.royal, trim: C.royalDeep, cols: 4, colsSide: 4 });
  // water tank
  const tg = new THREE.Group(); tg.position.set(-1.0, b.h + 0.18, -0.8); b.g.add(tg);
  for (const [lx, lz] of [[-0.35, -0.35], [0.35, -0.35], [-0.35, 0.35], [0.35, 0.35]]) boxB(tg, 0.08, 0.5, 0.08, C.navy, lx, 0, lz, { r: 0.02 });
  boxB(tg, 1.0, 0.9, 1.0, C.tealLight, 0, 0.5, 0, { r: 0.3 });
  boxB(tg, 1.08, 0.12, 1.08, C.teal, 0, 1.4, 0, { r: 0.05 });
  // antenna + blinking light
  boxB(b.g, 0.08, 1.8, 0.08, C.navy, 1.2, b.h + 0.18, 1.0, { r: 0.03 });
  const bl = boxB(b.g, 0.2, 0.2, 0.2, C.white, 1.2, b.h + 1.95, 1.0, { r: 0.08, material: new THREE.MeshStandardMaterial({ color: 0xffffff, emissive: 0x7ff3e4, emissiveIntensity: 0 }) });
  blinkers.push(bl);
  boxB(b.g, 1.4, 0.5, 0.9, C.stone, 1.0, b.h + 0.18, -1.2, { r: 0.12 });
}
// Mid-rise (green) with AC fans
{
  const b = building({ x: 3.25, z: -3.2, w: 4.6, d: 4.6, h: 6.1, color: C.green, trim: C.greenDeep, cols: 4, colsSide: 4 });
  for (const [ax, az] of [[-1.0, -0.9], [0.4, -0.9], [-1.0, 0.6]]){
    boxB(b.g, 1.0, 0.5, 1.0, C.stone, ax, b.h + 0.18, az, { r: 0.12 });
    const f = new THREE.Group(); f.position.set(ax, b.h + 0.71, az); b.g.add(f);
    box(f, 0.8, 0.04, 0.14, C.navy, 0, 0, 0, { r: 0.02 });
    box(f, 0.14, 0.04, 0.8, C.navy, 0, 0, 0, { r: 0.02 });
    fans.push(f);
  }
  boxB(b.g, 0.6, 0.9, 0.6, C.white, 1.3, b.h + 0.18, 1.2, { r: 0.12 });
}
// Low-rise (teal) with roof garden
{
  const b = building({ x: -3.2, z: 3.0, w: 4.4, d: 4.4, h: 4.7, color: C.teal, trim: 0x0f877d, cols: 3, colsSide: 3 });
  for (const [gx, gz] of [[-1.2, -1.1], [0, -1.1], [1.2, -1.1], [-1.2, 0.4], [1.2, 0.4]]){
    boxB(b.g, 0.8, 0.3, 0.8, C.white, gx, b.h + 0.18, gz, { r: 0.08 });
    boxB(b.g, 0.62, 0.42, 0.62, pick([C.green, C.greenLight, C.greenDeep]), gx, b.h + 0.42, gz, { r: 0.18 });
  }
}

/* ---------- the coffee shop ---------- */
const SHOP = { x: 2.7, z: 2.7 };
const steam = [];
let barista;
{
  const p = prop(SHOP.x, BY, SHOP.z, 0.22);
  const g = p.inner;
  const s = 3.8, half = s / 2;
  boxB(g, s + 0.1, 0.12, s + 0.1, C.white, 0, 0, 0, { r: 0.05 });
  // interior: counter, espresso machine, barista (visible through glass)
  boxB(g, 2.4, 0.55, 0.5, C.white, -0.2, 0.12, -0.3, { r: 0.08 });
  boxB(g, 0.6, 0.42, 0.36, C.royal, -0.7, 0.67, -0.35, { r: 0.08 });
  boxB(g, 0.3, 0.22, 0.3, C.orange, 0.3, 0.67, -0.3, { r: 0.08 });
  {
    const pr = person(C.white, { apron: true });
    pr.g.position.set(0, 0.12, -0.95); pr.g.rotation.y = -Math.PI / 2; pr.g.scale.setScalar(0.85);
    g.add(pr.g); barista = pr;
  }
  // ground-floor glass storefront
  boxB(g, s - 0.2, 1.3, s - 0.2, C.glass, 0, 0.12, 0, { r: 0.06, rough: 0.12, metal: 0.1, opacity: 0.42, cast: false });
  for (const cx of [-half, half]) for (const cz of [-half, half]) boxB(g, 0.22, 1.42, 0.22, C.white, cx, 0.1, cz, { r: 0.06 });
  for (const u of [-0.55, 0.55]){ boxB(g, 0.1, 1.3, 0.1, C.white, u, 0.12, half - 0.05, { r: 0.03 }); boxB(g, 0.1, 1.3, 0.1, C.white, half - 0.05, 0.12, u, { r: 0.03 }); }
  // door
  boxB(g, 0.72, 1.12, 0.1, C.teal, -1.2, 0.12, half - 0.02, { r: 0.04 });
  boxB(g, 0.5, 0.86, 0.12, C.tealLight, -1.2, 0.2, half - 0.01, { r: 0.04, rough: 0.2 });
  // upper floor
  boxB(g, s + 0.12, 0.16, s + 0.12, C.white, 0, 1.42, 0, { r: 0.05 });
  boxB(g, s, 1.5, s, C.white, 0, 1.58, 0, { r: 0.12 });
  windows(g, { w: s, d: s, y0: 2.45, floors: 1, fh: 1, cols: 3, colsSide: 3, ww: 0.7, wh: 0.62, color: C.royal });
  boxB(g, s + 0.16, 0.14, s + 0.16, C.tealLight, 0, 3.08, 0, { r: 0.05 });
  // sign band
  boxB(g, 1.9, 0.38, 0.12, C.orange, 0.5, 1.7, half + 0.02, { r: 0.08, emissive: C.orange, ei: 0.12 });
  boxB(g, 0.12, 0.38, 1.9, C.orange, half + 0.02, 1.7, -0.3, { r: 0.08, emissive: C.orange, ei: 0.12 });
  // striped awnings
  const stripes = 8;
  for (let i = 0; i < stripes; i++){
    const u = -half + 0.24 + i * ((s - 0.48) / (stripes - 1));
    const col = i % 2 ? C.white : C.orange;
    const a = box(g, 0.44, 0.07, 0.9, col, u, 1.36, half + 0.42, { r: 0.03 }); a.rotation.x = 0.36;
    const b = box(g, 0.9, 0.07, 0.44, col, half + 0.42, 1.36, u, { r: 0.03 }); b.rotation.z = -0.36;
  }
  // rooftop cup
  const cup = new THREE.Group(); cup.position.set(0.3, 3.15, -0.2); g.add(cup);
  boxB(cup, 1.0, 1.1, 1.0, C.white, 0, 0, 0, { r: 0.22 });
  boxB(cup, 1.06, 0.3, 1.06, C.orange, 0, 0.38, 0, { r: 0.1 });
  boxB(cup, 1.1, 0.1, 1.1, C.navy, 0, 1.08, 0, { r: 0.04 });
  box(cup, 0.18, 0.5, 0.16, C.white, 0.62, 0.6, 0, { r: 0.07 });
  for (let i = 0; i < 6; i++){
    const m = new THREE.Mesh(geo(0.32, 0.32, 0.32, 0.12), new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.9, transparent: true, opacity: 0.8 }));
    m.castShadow = false; cup.add(m);
    steam.push({ m, phase: i / 6 });
  }
  // planters by the door
  for (const px of [-2.0, -0.4]){ boxB(g, 0.42, 0.34, 0.42, C.white, px, 0, half + 0.55, { r: 0.1 }); boxB(g, 0.38, 0.4, 0.38, C.green, px, 0.32, half + 0.55, { r: 0.16 }); }
}

/* ---------- people ---------- */
function person(shirt, o = {}){
  const g = new THREE.Group();
  const skin = o.skin ?? pick(C.skin), pants = o.pants ?? pick([C.navy, 0x3a4566, 0x5d6a86]), hair = pick(C.hair);
  const legs = [];
  for (const sz of [-0.075, 0.075]){
    const lg = new THREE.Group(); lg.position.set(0, 0.34, sz);
    box(lg, 0.12, 0.34, 0.11, pants, 0, -0.17, 0, { r: 0.04 });
    g.add(lg); legs.push(lg);
  }
  box(g, 0.22, 0.38, 0.32, shirt, 0, 0.53, 0, { r: 0.08 });
  if (o.apron) box(g, 0.04, 0.3, 0.26, C.orange, 0.12, 0.5, 0, { r: 0.015 });
  const arms = [];
  for (const sz of [-0.2, 0.2]){
    const ag = new THREE.Group(); ag.position.set(0, 0.68, sz);
    box(ag, 0.1, 0.3, 0.08, shirt, 0, -0.14, 0, { r: 0.035 });
    g.add(ag); arms.push(ag);
  }
  box(g, 0.2, 0.2, 0.2, skin, 0, 0.84, 0, { r: 0.07 });
  box(g, 0.22, 0.08, 0.22, hair, -0.01, 0.96, 0, { r: 0.035 });
  return { g, legs, arms };
}
const shirts = [C.royal, C.teal, C.green, C.white, C.navy, C.tealLight, C.greenLight, C.royalDeep];

// queue path (world coords on block sidewalk)
const QP = [[6.05, 6.15], [5.6, 5.3], [4.9, 5.3], [4.2, 5.3], [3.5, 5.3], [2.8, 5.3], [2.15, 5.25], [1.5, 4.75], [1.5, 4.75]];
const QN = 8, STEP = LOOP / QN;
const queue = [];
for (let k = 0; k < QN; k++){
  const p = prop(QP[k][0], BY, QP[k][1]);
  const pr = person(shirts[k % shirts.length]);
  pr.g.scale.setScalar(0.85);
  p.inner.add(pr.g);
  // a few carry an orange cup
  queue.push({ p, pr, k });
}

// café tables with sipping customers on the side sidewalk
const sippers = [];
for (const [tx, tz, ph] of [[5.55, 1.5, 0], [5.55, 3.3, 0.5]]){
  const p = prop(tx, BY, tz);
  const g = p.inner;
  boxB(g, 0.08, 1.4, 0.08, C.navy, 0, 0, 0, { r: 0.03 });
  const um = boxB(g, 1.5, 0.1, 1.5, C.orange, 0, 1.4, 0, { r: 0.05 });
  boxB(g, 0.7, 0.06, 0.7, C.white, 0, 0.5, 0, { r: 0.03 });
  boxB(g, 0.06, 0.5, 0.06, C.navy, 0, 0, 0, { r: 0.02 });
  boxB(g, 0.16, 0.16, 0.16, C.white, 0.12, 0.56, 0.12, { r: 0.04 });
  for (const sz of [-0.55, 0.55]){
    boxB(g, 0.36, 0.3, 0.36, C.teal, 0, 0, sz, { r: 0.06 });
    const pr = person(pick(shirts));
    pr.g.scale.setScalar(0.82);
    pr.g.position.set(0, 0.06, sz);
    pr.g.rotation.y = sz > 0 ? Math.PI / 2 : -Math.PI / 2;
    pr.legs.forEach(l => (l.rotation.z = Math.PI / 2.2));
    g.add(pr.g);
    const cupM = box(pr.arms[0], 0.12, 0.14, 0.12, C.white, 0, -0.3, 0, { r: 0.04 });
    box(cupM, 0.13, 0.05, 0.13, C.orange, 0, 0, 0, { r: 0.02 });
    sippers.push({ pr, ph: ph + (sz > 0 ? 0.25 : 0) });
  }
}

/* ---------- vehicles ---------- */
function wheel(parent, x, y, z, r, side){
  const w = new THREE.Group(); w.position.set(x, y, z); parent.add(w);
  box(w, r * 2, r * 2, 0.14, C.tire, 0, 0, 0, { r: r * 0.45 });
  box(w, r * 0.9, r * 0.9, 0.04, C.stone, 0, 0, side * 0.07, { r: 0.02 });
  return w;
}
function car(color){
  const g = new THREE.Group(), wheels = [];
  box(g, 1.5, 0.4, 0.82, color, 0, 0.38, 0, { r: 0.15 });
  box(g, 0.86, 0.34, 0.74, C.glass, -0.1, 0.72, 0, { r: 0.12, rough: 0.18, metal: 0.1 });
  box(g, 0.82, 0.07, 0.72, color, -0.1, 0.9, 0, { r: 0.03 });
  for (const s of [-0.26, 0.26]){
    box(g, 0.05, 0.09, 0.16, C.white, 0.75, 0.42, s, { r: 0.02, emissive: 0xfff3d6, ei: 0.5, cast: false });
    box(g, 0.05, 0.09, 0.16, C.navy, -0.75, 0.42, s, { r: 0.02, cast: false });
  }
  for (const wx of [-0.48, 0.48]) for (const wz of [-0.38, 0.38]) wheels.push(wheel(g, wx, 0.17, wz, 0.17, Math.sign(wz)));
  return { g, wheels, r: 0.17 };
}
function bus(color){
  const g = new THREE.Group(), wheels = [];
  box(g, 3.0, 0.95, 0.95, color, 0, 0.66, 0, { r: 0.18 });
  box(g, 2.7, 0.34, 0.98, C.glass, -0.05, 0.86, 0, { r: 0.08, rough: 0.18 });
  box(g, 0.06, 0.5, 0.8, C.glass, 1.49, 0.8, 0, { r: 0.03, rough: 0.18 });
  box(g, 2.9, 0.08, 0.9, C.white, 0, 1.16, 0, { r: 0.03 });
  box(g, 0.8, 0.18, 0.6, C.white, -0.4, 1.28, 0, { r: 0.06 });
  for (const wx of [-1.0, 1.0]) for (const wz of [-0.44, 0.44]) wheels.push(wheel(g, wx, 0.2, wz, 0.2, Math.sign(wz)));
  return { g, wheels, r: 0.2 };
}
function scooter(){
  const g = new THREE.Group(), wheels = [];
  box(g, 0.66, 0.16, 0.26, C.white, 0, 0.3, 0, { r: 0.06 });
  box(g, 0.24, 0.24, 0.26, C.teal, 0.26, 0.42, 0, { r: 0.07 });
  box(g, 0.07, 0.42, 0.07, C.navy, 0.34, 0.6, 0, { r: 0.025 });
  box(g, 0.06, 0.05, 0.42, C.navy, 0.34, 0.82, 0, { r: 0.02 });
  box(g, 0.3, 0.08, 0.24, C.navy, -0.1, 0.44, 0, { r: 0.03 });
  box(g, 0.38, 0.36, 0.38, C.orange, -0.34, 0.68, 0, { r: 0.07, emissive: C.orange, ei: 0.08 });
  // rider
  box(g, 0.22, 0.36, 0.3, C.royal, -0.04, 0.68, 0, { r: 0.08 });
  for (const sz of [-0.13, 0.13]){ const a = box(g, 0.34, 0.08, 0.08, C.royal, 0.14, 0.76, sz, { r: 0.03 }); a.rotation.z = -0.4; }
  box(g, 0.2, 0.18, 0.2, pick(C.skin), -0.02, 0.96, 0, { r: 0.07 });
  box(g, 0.26, 0.14, 0.26, C.teal, -0.03, 1.08, 0, { r: 0.1 });
  for (const wx of [-0.3, 0.32]) wheels.push(wheel(g, wx, 0.14, 0, 0.14, 1));
  return { g, wheels, r: 0.14 };
}

const innerLane = makePath(7.75, 1.4), outerLane = makePath(9.55, 1.8), bikeLane = makePath(6.88, 1.0);
const vehicles = [];
function addVehicle(v, path, rev, offset){
  const p = prop(0, RY, 0);
  p.inner.add(v.g);
  vehicles.push({ ...v, p, path, rev, offset, K: Math.max(1, Math.round(path.L / (TAU * v.r))) });
}
[C.royal, C.white, C.teal].forEach((c, i) => addVehicle(car(c), innerLane, false, i * innerLane.L / 3 + 3));
addVehicle(bus(C.green), outerLane, true, 0);
[C.royalDeep, C.tealLight].forEach((c, i) => addVehicle(car(c), outerLane, true, (i + 1) * outerLane.L / 3));

// scooters parked at the shop curb, leave on a delivery lap and come back
const k0 = 6.88 - 1.0;
const scooters = [
  { s0: 4.25 + k0, dep: 1.5, dur: 7.0 },
  { s0: 3.35 + k0, dep: 3.0, dur: 7.0 }
].map(sc => {
  const v = scooter();
  const p = prop(0, RY, 0);
  p.inner.add(v.g);
  return { ...sc, ...v, p, K: Math.round(bikeLane.L / (TAU * v.r)) };
});

/* ---------- street furniture ---------- */
const trees = [];
function tree(x, z, y = 0, size = 1){
  const p = prop(x, y, z);
  const g = p.inner; g.scale.setScalar(size);
  boxB(g, 0.5, 0.12, 0.5, C.stone, 0, 0, 0, { r: 0.05 });
  boxB(g, 0.16, 0.8, 0.16, C.trunk, 0, 0.1, 0, { r: 0.05 });
  const fol = new THREE.Group(); fol.position.y = 0.8; g.add(fol);
  const c1 = pick([C.green, C.greenDeep, C.teal]);
  box(fol, 0.95, 0.85, 0.95, c1, 0, 0.42, 0, { r: 0.3 });
  box(fol, 0.66, 0.6, 0.66, pick([C.greenLight, C.green]), 0.08, 1.0, -0.05, { r: 0.22 });
  fol.rotation.y = rnd() * TAU;
  trees.push({ fol, ph: rnd() * TAU });
}
function lamp(x, z, rotY, y = 0){
  const p = prop(x, y, z);
  const g = p.inner; g.rotation.y = rotY;
  boxB(g, 0.28, 0.1, 0.28, C.navy, 0, 0, 0, { r: 0.04 });
  boxB(g, 0.09, 2.3, 0.09, C.navy, 0, 0.05, 0, { r: 0.03 });
  box(g, 0.62, 0.07, 0.07, C.navy, 0.28, 2.32, 0, { r: 0.02 });
  box(g, 0.36, 0.12, 0.22, C.navy, 0.56, 2.26, 0, { r: 0.05 });
  box(g, 0.28, 0.04, 0.16, C.white, 0.56, 2.19, 0, { r: 0.015, emissive: 0xfff1d0, ei: 0.9, cast: false });
}
function bench(x, z, rotY){
  const p = prop(x, 0, z);
  const g = p.inner; g.rotation.y = rotY;
  for (const lx of [-0.4, 0.4]) boxB(g, 0.08, 0.3, 0.34, C.navy, lx, 0, 0, { r: 0.02 });
  boxB(g, 1.1, 0.08, 0.38, C.teal, 0, 0.3, 0, { r: 0.03 });
  boxB(g, 1.1, 0.3, 0.06, C.teal, 0, 0.38, -0.17, { r: 0.03 });
}
function hydrant(x, z, y){
  const p = prop(x, y, z);
  boxB(p.inner, 0.2, 0.36, 0.2, C.royal, 0, 0, 0, { r: 0.07 });
  box(p.inner, 0.32, 0.08, 0.1, C.royal, 0, 0.22, 0, { r: 0.03 });
  boxB(p.inner, 0.24, 0.07, 0.24, C.royalDeep, 0, 0.36, 0, { r: 0.03 });
}
function bin(x, z, y){
  const p = prop(x, y, z);
  boxB(p.inner, 0.3, 0.46, 0.3, C.greenDeep, 0, 0, 0, { r: 0.07 });
  boxB(p.inner, 0.34, 0.06, 0.34, C.navy, 0, 0.46, 0, { r: 0.02 });
}

// outer ring (slab sidewalk between road and edge)
const O = 11.8;
for (const u of [-9.5, -4.5, 1.5, 6.5]){ tree(u, -O); tree(-O, u); }
for (const u of [-8, -2.5]){ tree(u, O, 0, 0.9); tree(O, u, 0, 0.9); }
tree(O, O, 0, 1.1); tree(-O, -O, 0, 1.2); tree(O, -O, 0, 1.05); tree(-O, O, 0, 1.05);
for (const u of [-6.5, 4.0]){ lamp(u, 11.0, Math.PI / 2); lamp(11.0, u, 0); lamp(u, -11.0, -Math.PI / 2); lamp(-11.0, u, Math.PI); }
bench(9.0, 12.2, Math.PI); bench(12.2, 8.5, -Math.PI / 2); bench(-1.5, -12.2, 0);
// inner block sidewalk
lamp(6.0, -1.0, Math.PI, BY); lamp(-1.0, 6.0, -Math.PI / 2, BY); lamp(-6.0, 0.4, 0, BY);
tree(-0.1, 1.7, BY, 0.85); tree(-0.1, 4.4, BY, 0.8); tree(0.3, -5.8, BY, 0.75);
hydrant(6.0, -2.4, BY); bin(0.6, 5.9, BY); bin(6.0, 0.5, BY);

// pedestrians on the outer sidewalk
const walkers = [];
function addWalker(axis, fixed, from, to, shirt, dog){
  const p = prop(0, 0, 0);
  const pr = person(shirt); pr.g.scale.setScalar(0.85); p.inner.add(pr.g);
  let d = null;
  if (dog){
    d = new THREE.Group(); p.inner.add(d);
    box(d, 0.42, 0.2, 0.18, C.white, 0, 0.24, 0, { r: 0.07 });
    box(d, 0.18, 0.18, 0.16, C.white, 0.26, 0.36, 0, { r: 0.06 });
    box(d, 0.06, 0.08, 0.16, C.navy, 0.3, 0.46, 0, { r: 0.02 });
    for (const lx of [-0.14, 0.14]) for (const lz of [-0.06, 0.06]) boxB(d, 0.06, 0.14, 0.06, C.navy, lx, 0, lz, { r: 0.02 });
    box(d, 0.14, 0.04, 0.04, C.white, -0.26, 0.34, 0, { r: 0.015 });
  }
  walkers.push({ p, pr, axis, fixed, from, to, d });
}
addWalker('x', 11.6, -12.4, 12.4, C.royal, true);
addWalker('x', 12.3, 12.4, -12.4, C.green, false);
addWalker('z', 11.7, 12.4, -12.4, C.teal, false);
addWalker('z', 12.35, -12.4, 12.4, C.white, false);

/* ---------- post-processing ---------- */
const rt = new THREE.WebGLRenderTarget(W, H, { type: THREE.HalfFloatType, samples: 4 });
const composer = new EffectComposer(renderer, rt);
composer.setPixelRatio(1);
composer.setSize(W, H);
composer.addPass(new RenderPass(scene, camera));
try {
  const gtao = new GTAOPass(scene, camera, W, H);
  gtao.output = GTAOPass.OUTPUT.Default;
  gtao.blendIntensity = 1.0;
  gtao.updateGtaoMaterial({ radius: 0.7, distanceExponent: 1.4, thickness: 1.2, scale: 1.15, samples: 12, distanceFallOff: 1, screenSpaceRadius: false });
  gtao.updatePdMaterial({ lumaPhi: 10, depthPhi: 2, normalPhi: 3, radius: 6, radiusExponent: 1, rings: 2, samples: 16 });
  composer.addPass(gtao);
} catch (e) { console.warn('GTAO unavailable', e); }
composer.addPass(new OutputPass());

/* ---------- overlay stats ---------- */
const elO = document.getElementById('sOrders'), elR = document.getElementById('sRev'), elD = document.getElementById('sDel'), elDR = document.getElementById('dRev');
const fmtInt = n => n.toLocaleString('en-US');
const price = i => { const x = Math.sin(i * 12.9898) * 43758.5453; return 3.5 + (x - Math.floor(x)) * 6.5; };
let lastOrders = -1, lastDel = -1, revTarget = 6842.5, revShown = 6842.5, revIdx = 0;
function bump(el){ el.classList.remove('bump'); void el.offsetWidth; el.classList.add('bump'); }
function updateStats(t, lt){
  const n = Math.floor((t + 0.3) / STEP);
  while (revIdx < n){ revTarget += price(revIdx++); }
  const orders = 1284 + n;
  if (orders !== lastOrders){ elO.textContent = fmtInt(orders); if (lastOrders >= 0) bump(elO); lastOrders = orders; }
  const del = 212 + 2 * Math.floor(t / LOOP) + (lt >= 1.5) + (lt >= 3.0);
  if (del !== lastDel){ elD.textContent = fmtInt(del); if (lastDel >= 0) bump(elD); lastDel = del; }
  const prev = Math.floor(revShown);
  revShown += (revTarget - revShown) * 0.12;
  if (Math.floor(revShown) !== prev){
    elR.textContent = '$' + fmtInt(Math.floor(revShown));
    elDR.textContent = 'avg ticket $' + (revShown / orders).toFixed(2);
  }
  if (revTarget - revShown > 2 && !elR.classList.contains('bump')) bump(elR);
}

/* ---------- animation ---------- */
let start = null;
const card = document.querySelector('.card');
function restart(){
  start = null; buildDone = false;
  lastOrders = -1; lastDel = -1; revTarget = 6842.5; revShown = 6842.5; revIdx = 0;
  elR.textContent = '$6,842';
  card.style.animation = 'none'; void card.offsetWidth; card.style.animation = '';
}
addEventListener('keydown', e => { if (e.code === 'Space' || e.key === 'r' || e.key === 'R') { e.preventDefault(); restart(); } });
addEventListener('pointerdown', restart);
function frame(now){
  if (start === null) start = now;
  const t = (now - start) / 1000, lt = t % LOOP, ph = lt / LOOP;
  applyBuild(t);

  // camera: eased sway-orbit with gentle push in, period = LOOP
  const az = Math.PI / 4 + 0.3 * Math.sin(ph * TAU);
  const push = (1 - Math.cos(ph * TAU)) / 2;
  const R = 70 - 8 * push, el = 0.58 + 0.03 * Math.sin(ph * TAU);
  camera.position.set(Math.sin(az) * Math.cos(el) * R, Math.sin(el) * R, Math.cos(az) * Math.cos(el) * R);
  camera.lookAt(2.5, 0.9, 2.5);

  // cars: one lap per loop
  for (const v of vehicles){
    const pt = v.path.at(v.offset + ph * v.path.L, v.rev);
    v.p.root.position.set(pt.x, RY, pt.z);
    v.p.root.rotation.y = pt.yaw;
    const spin = -ph * TAU * v.K;
    v.wheels.forEach(w => (w.rotation.z = spin));
  }

  // scooters
  for (const sc of scooters){
    const u = smooth((lt - sc.dep) / sc.dur);
    const pt = bikeLane.at(sc.s0 + u * bikeLane.L, false);
    const lean = Math.sin(u * Math.PI);
    sc.p.root.position.set(pt.x, RY, pt.z);
    sc.p.root.rotation.y = pt.yaw;
    sc.g.position.y = 0.03 * lean * Math.abs(Math.sin(lt * 18));
    sc.wheels.forEach(w => (w.rotation.z = -u * TAU * sc.K));
  }

  // queue: every STEP seconds everyone shuffles forward one slot
  const step = Math.floor(lt / STEP), fr = (lt % STEP) / STEP;
  const move = smooth(fr / 0.5);
  for (const q of queue){
    const u = (q.k + step + move) % QN;
    const i = Math.floor(u), f = u - i;
    const a = QP[i], b = QP[i + 1];
    const x = a[0] + (b[0] - a[0]) * f, z = a[1] + (b[1] - a[1]) * f;
    q.p.root.position.set(x, BY, z);
    const dx = b[0] - a[0], dz = b[1] - a[1];
    if (Math.hypot(dx, dz) > 0.01) q.p.root.rotation.y = Math.atan2(-dz, dx);
    let s = 1;
    if (u < 1) s = smooth(u * 1.4);
    else if (u >= 6) s = 1 - smooth((u - 6) / 0.9);
    q.pr.g.scale.setScalar(Math.max(0.001, 0.85 * s));
    q.pr.g.visible = s > 0.01;
    const moving = fr < 0.5 ? Math.sin(fr / 0.5 * Math.PI) : 0;
    const sw = Math.sin(lt * 14 + q.k) * 0.55 * moving;
    q.pr.legs[0].rotation.z = sw; q.pr.legs[1].rotation.z = -sw;
    q.pr.g.position.y = Math.abs(Math.sin(lt * 14 + q.k)) * 0.04 * moving;
  }

  // walkers along the outer sidewalk
  for (const w of walkers){
    const v = w.from + (w.to - w.from) * ph;
    const dir = Math.sign(w.to - w.from);
    if (w.axis === 'x'){ w.p.root.position.set(v, 0, w.fixed); w.p.root.rotation.y = dir > 0 ? 0 : Math.PI; }
    else { w.p.root.position.set(w.fixed, 0, v); w.p.root.rotation.y = dir > 0 ? -Math.PI / 2 : Math.PI / 2; }
    const edge = Math.min(Math.abs(v - w.from), Math.abs(v - w.to));
    const s = smooth(edge / 0.8);
    w.p.root.scale.setScalar(Math.max(0.001, s));
    const sw = Math.sin(ph * TAU * 14) * 0.55;
    w.pr.legs[0].rotation.z = sw; w.pr.legs[1].rotation.z = -sw;
    w.pr.arms[0].rotation.z = -sw * 0.6; w.pr.arms[1].rotation.z = sw * 0.6;
    w.pr.g.position.y = Math.abs(Math.sin(ph * TAU * 14)) * 0.035;
    if (w.d){ w.d.position.set(0.75, Math.abs(Math.sin(ph * TAU * 28)) * 0.05, 0.35); }
  }

  // ambient motion
  for (const tr of trees){ tr.fol.rotation.z = 0.035 * Math.sin(ph * TAU * 2 + tr.ph); tr.fol.rotation.x = 0.025 * Math.cos(ph * TAU * 2 + tr.ph); }
  fans.forEach((f, i) => (f.rotation.y = ph * TAU * (6 + i)));
  blinkers.forEach(b => (b.material.emissiveIntensity = (lt % 1) < 0.35 ? 2.2 : 0));
  for (const st of steam){
    const u = (ph * 4 + st.phase) % 1;
    st.m.position.set(Math.sin(u * TAU + st.phase * 9) * 0.14, 1.25 + u * 1.7, Math.cos(u * 5 + st.phase * 4) * 0.12);
    st.m.scale.setScalar(0.35 + u * 1.1);
    st.m.material.opacity = 0.85 * Math.sin(u * Math.PI);
    st.m.rotation.y = u * 2;
  }
  for (const sp of sippers){
    const u = (ph * 2 + sp.ph) % 1;
    const lift = smooth(u / 0.2) * (1 - smooth((u - 0.45) / 0.2));
    sp.pr.arms[0].rotation.z = 1.9 * lift;
    sp.pr.g.position.y = 0.06;
  }
  if (barista){
    barista.g.position.x = 0.6 * Math.sin(ph * TAU * 2);
    const sw = Math.sin(ph * TAU * 16) * 0.3;
    barista.arms[0].rotation.z = 0.9 + sw; barista.arms[1].rotation.z = 0.9 - sw;
  }

  updateStats(t, lt);
  composer.render();
  requestAnimationFrame(frame);
}
window.__sceneOK = true;
requestAnimationFrame(frame);
</script>
</body>
</html>
canh-3d-video-doc/02-quan-ca-phe-ben-trong.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
</head>
<body>
<title>Daily Grind Interior</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,800&family=Manrope:wght@500;600;700;800&display=swap">
<style>
/* Layout: fixed 1088x1920 frame scaled to fit the window; frosted card floats over the top third, diorama sits low. */
:root{
  --bg:#e9ecf1;
  --frame:#f6f7f9;
  --ink:#141b38;
  --muted:#5a6383;
  --accent:#ff7a1c;
  --royal:#2f55e6;
  --teal:#17a99c;
  --green:#3db86a;
  --f-display:'Bricolage Grotesque','Manrope',system-ui,sans-serif;
  --f-body:'Manrope',system-ui,-apple-system,'Segoe UI',sans-serif;
  color-scheme:light;
}
html,body{height:100%;margin:0;overflow:hidden;background:var(--bg);color:var(--ink)}
#stage{
  position:absolute;left:50%;top:50%;
  width:1088px;height:1920px;
  transform:translate(-50%,-50%) scale(var(--s,0.4));
  transform-origin:center center;
  overflow:hidden;background:var(--frame);
}
#c{position:absolute;inset:0;display:block;width:1088px;height:1920px}
.vignette{position:absolute;inset:0;pointer-events:none;
  background:radial-gradient(120% 80% at 50% 60%, rgba(255,255,255,0) 55%, rgba(20,27,56,.07) 100%)}

.card{
  position:absolute;left:84px;right:84px;top:132px;
  padding:42px 48px 44px;
  border-radius:44px;
  background:linear-gradient(160deg, rgba(255,255,255,.62), rgba(255,255,255,.34));
  -webkit-backdrop-filter:blur(26px) saturate(1.5);
  backdrop-filter:blur(26px) saturate(1.5);
  border:1.5px solid rgba(255,255,255,.85);
  box-shadow:0 30px 80px -30px rgba(20,27,56,.35), inset 0 1px 0 rgba(255,255,255,.9);
  font-family:var(--f-body);
  opacity:0;transform:translateY(-24px) scale(.98);
  animation:cardIn .7s cubic-bezier(.2,.9,.25,1.15) .55s forwards;
}
@keyframes cardIn{to{opacity:1;transform:none}}
.head{display:flex;align-items:center;justify-content:space-between;gap:24px}
.brand{display:flex;align-items:center;gap:22px}
.mark{width:68px;height:68px;border-radius:22px;background:var(--accent);position:relative;
  box-shadow:0 10px 24px -8px rgba(255,122,28,.7)}
.mark::before{content:"";position:absolute;left:18px;top:22px;width:26px;height:28px;border-radius:5px 5px 10px 10px;background:#fff}
.mark::after{content:"";position:absolute;left:42px;top:27px;width:9px;height:13px;border:4px solid #fff;border-left:0;border-radius:0 8px 8px 0}
h1{margin:0;font-family:var(--f-display);font-weight:800;font-size:56px;line-height:1;letter-spacing:-.02em;text-wrap:balance}
h1 span{color:var(--muted);font-weight:600}
.sub{margin:10px 0 0;font-size:22px;font-weight:600;color:var(--muted);letter-spacing:.01em}
.live{display:flex;align-items:center;gap:12px;padding:12px 20px;border-radius:999px;
  background:rgba(20,27,56,.9);color:#fff;font-weight:800;font-size:20px;letter-spacing:.16em}
.live i{width:14px;height:14px;border-radius:50%;background:var(--accent);box-shadow:0 0 0 0 rgba(255,122,28,.7);animation:pulse 1s ease-out infinite}
@keyframes pulse{0%{box-shadow:0 0 0 0 rgba(255,122,28,.75)}100%{box-shadow:0 0 0 16px rgba(255,122,28,0)}}
.stats{display:grid;grid-template-columns:1fr 1.25fr 1fr;gap:0;margin-top:36px;
  border-top:1.5px solid rgba(20,27,56,.09)}
.stat{padding:30px 0 0 28px;display:flex;flex-direction:column;gap:10px;min-width:0;border-left:1.5px solid rgba(20,27,56,.09)}
.stat:first-child{padding-left:0;border-left:0}
.label{font-size:19px;font-weight:800;text-transform:uppercase;letter-spacing:.14em;color:var(--muted);display:flex;align-items:center;gap:10px}
.label b{width:12px;height:12px;border-radius:4px;display:inline-block}
.val{font-family:var(--f-body);font-weight:800;font-size:66px;line-height:1;letter-spacing:-.03em;
  font-variant-numeric:tabular-nums;color:var(--ink);display:inline-block;transform-origin:left bottom}
.val.bump{animation:bump .55s ease-out}
@keyframes bump{0%{color:var(--accent);transform:translateY(-6px) scale(1.04)}100%{color:var(--ink);transform:none}}
.delta{font-size:20px;font-weight:700;color:var(--teal);font-variant-numeric:tabular-nums}
@media (prefers-reduced-motion: reduce){.card{animation-duration:.01s}.live i{animation:none}}
</style>

<div id="stage">
  <canvas id="c" width="1088" height="1920"></canvas>
  <div class="vignette"></div>
  <section class="card" aria-label="Daily Grind live sales">
    <div class="head">
      <div class="brand">
        <div class="mark" aria-hidden="true"></div>
        <div>
          <h1>Daily Grind <span>· Live Sales</span></h1>
          <p class="sub">5th &amp; Pine corner store · today</p>
        </div>
      </div>
      <div class="live"><i></i>LIVE</div>
    </div>
    <div class="stats">
      <div class="stat">
        <span class="label"><b style="background:var(--royal)"></b>Orders</span>
        <span class="val" id="sOrders">1,284</span>
        <span class="delta" id="dOrders">+48 / hr</span>
      </div>
      <div class="stat">
        <span class="label"><b style="background:var(--accent)"></b>Revenue</span>
        <span class="val" id="sRev">$6,842</span>
        <span class="delta" id="dRev">avg ticket $6.10</span>
      </div>
      <div class="stat">
        <span class="label"><b style="background:var(--green)"></b>Deliveries</span>
        <span class="val" id="sDel">212</span>
        <span class="delta">2 riders out</span>
      </div>
    </div>
  </section>
</div>

<div id="err" hidden style="position:fixed;left:16px;right:16px;bottom:16px;padding:14px 16px;border-radius:12px;background:#141b38;color:#fff;font:600 14px/1.4 Manrope,system-ui,sans-serif;z-index:9"></div>
<script>
(function(){
  var el=document.getElementById('err');
  function show(m){ el.hidden=false; el.textContent='Không chạy được cảnh 3D: '+m; }
  window.addEventListener('error',function(e){ show(e.message||'lỗi tải script'); },true);
  window.addEventListener('unhandledrejection',function(e){ show(String(e.reason&&e.reason.message||e.reason)); });
  setTimeout(function(){ if(!window.__sceneOK) show('thư viện Three.js chưa tải xong sau 15 giây (mạng hoặc CDN bị chặn).'); },15000);
})();
</script>
<script type="importmap">
{ "imports": {
  "three": "https://cdn.jsdelivr.net/npm/three@0.160.0/+esm"
} }
</script>

<script type="module">
import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.160.0/+esm';
import { RoundedBoxGeometry } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/geometries/RoundedBoxGeometry.js/+esm';
import { EffectComposer } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/EffectComposer.js/+esm';
import { RenderPass } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/RenderPass.js/+esm';
import { GTAOPass } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/GTAOPass.js/+esm';
import { OutputPass } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/OutputPass.js/+esm';

const W = 1088, H = 1920, LOOP = 10, TAU = Math.PI * 2;

/* ---------- fit frame to window ---------- */
const stage = document.getElementById('stage');
function fit(){ stage.style.setProperty('--s', Math.min(innerWidth / W, innerHeight / H)); }
addEventListener('resize', fit); fit();

/* ---------- palette ---------- */
const C = {
  ground:0xf7f6f2, base:0x2a48d4, road:0xd2d7e0, walk:0xe6e9ee, line:0xffffff,
  royal:0x2f55e6, royalDeep:0x2340b8, teal:0x17a99c, tealLight:0x93e0d6,
  green:0x3db86a, greenDeep:0x22864a, greenLight:0x92dba6,
  orange:0xff7a1c, white:0xffffff, navy:0x1d2547, tire:0x2b3040, glass:0xcdeef4,
  trunk:0x8d847b, stone:0xc9ced8,
  skin:[0xf2cba8,0xdba57e,0xae7652,0x7d5136], hair:[0x2b2420,0x5a3b25,0x1d2547,0xd9b77a]
};

/* ---------- seeded random ---------- */
function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296}}
const rnd = mulberry32(11);
const pick = arr => arr[Math.floor(rnd() * arr.length)];
const clamp01 = x => Math.min(1, Math.max(0, x));
const smooth = x => { x = clamp01(x); return x * x * (3 - 2 * x); };
const easeOutCubic = x => 1 - Math.pow(1 - x, 3);
const mod = (a, n) => ((a % n) + n) % n;
const easeOutBack = x => { const c1 = 2.1, c3 = c1 + 1; return 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2); };

/* ---------- renderer ---------- */
const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('c'), antialias: true, powerPreference: 'high-performance' });
renderer.setPixelRatio(1);
renderer.setSize(W, H, false);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;

const scene = new THREE.Scene();
scene.background = new THREE.Color(0xf7f8fa);

const camera = new THREE.PerspectiveCamera(32, W / H, 0.5, 150);
camera.setViewOffset(W, H, 0, -300, W, H); // drop the diorama below the card

/* ---------- lights ---------- */
scene.add(new THREE.HemisphereLight(0xeef3ff, 0xd8d3c8, 1.35));
const sun = new THREE.DirectionalLight(0xfff4e6, 2.7);
sun.position.set(-12, 26, 14);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
Object.assign(sun.shadow.camera, { left:-20, right:20, top:20, bottom:-20, near:1, far:80 });
sun.shadow.bias = -0.0004;
sun.shadow.normalBias = 0.025;
sun.shadow.radius = 5;
scene.add(sun);

/* ---------- geometry + material helpers ---------- */
const geoCache = new Map(), matCache = new Map();
function geo(w, h, d, r){
  r = r ?? Math.min(0.14, Math.min(w, h, d) * 0.22);
  r = Math.min(r, Math.min(w, h, d) / 2 - 0.001);
  const k = [w, h, d, r].map(v => v.toFixed(3)).join('|');
  if (!geoCache.has(k)) geoCache.set(k, new RoundedBoxGeometry(w, h, d, 2, r));
  return geoCache.get(k);
}
function mat(color, o = {}){
  const k = [color, o.rough, o.metal, o.emissive, o.ei, o.opacity].join('|');
  if (!matCache.has(k)) matCache.set(k, new THREE.MeshStandardMaterial({
    color, roughness: o.rough ?? 0.62, metalness: o.metal ?? 0,
    emissive: o.emissive ?? 0x000000, emissiveIntensity: o.ei ?? 1,
    transparent: o.opacity !== undefined, opacity: o.opacity ?? 1
  }));
  return matCache.get(k);
}
function box(parent, w, h, d, color, x = 0, y = 0, z = 0, o = {}){
  const m = new THREE.Mesh(geo(w, h, d, o.r), o.material || mat(color, o));
  m.position.set(x, y, z);
  m.castShadow = o.cast !== false;
  m.receiveShadow = true;
  parent.add(m);
  return m;
}
// bottom-aligned box
const boxB = (p, w, h, d, c, x, y, z, o) => box(p, w, h, d, c, x, y + h / 2, z, o);

/* ---------- build-in system ---------- */
const builds = [];
function prop(x, y, z, delay){
  const root = new THREE.Group(); root.position.set(x, y, z);
  const inner = new THREE.Group(); root.add(inner);
  scene.add(root);
  const dist = Math.hypot(x, z);
  builds.push({ inner, delay: delay ?? (0.16 + (dist / 18) * 0.5 + rnd() * 0.12) });
  return { root, inner };
}
let buildDone = false;
function applyBuild(t){
  if (buildDone) return;
  let all = true;
  for (const b of builds){
    const x = clamp01((t - b.delay) / 0.42);
    if (x < 1) all = false;
    b.inner.visible = x > 0;
    b.inner.scale.setScalar(Math.max(0.001, easeOutBack(x)));
    b.inner.position.y = -1.6 * (1 - easeOutCubic(x));
  }
  if (all) buildDone = true;
}

/* ---------- lane path: rounded rectangle, arc-length param ---------- */
function makePath(h, rc){
  const a = 2 * (h - rc), arc = Math.PI * rc / 2, L = 4 * a + 4 * arc, k = h - rc;
  const starts = [[-k, h], [h, k], [k, -h], [-h, -k]];
  const dirs = [[1, 0], [0, -1], [-1, 0], [0, 1]];
  const centers = [[k, k], [k, -k], [-k, -k], [-k, k]];
  const th0 = [Math.PI / 2, 0, -Math.PI / 2, -Math.PI];
  return { L, at(s, rev){
    if (rev) s = L - s;
    s = ((s % L) + L) % L;
    const seg = a + arc, i = Math.min(3, Math.floor(s / seg)), r = s - i * seg;
    let x, z, dx, dz;
    if (r < a){ x = starts[i][0] + dirs[i][0] * r; z = starts[i][1] + dirs[i][1] * r; dx = dirs[i][0]; dz = dirs[i][1]; }
    else { const th = th0[i] - (r - a) / rc; x = centers[i][0] + rc * Math.cos(th); z = centers[i][1] + rc * Math.sin(th); dx = Math.sin(th); dz = -Math.cos(th); }
    if (rev){ dx = -dx; dz = -dz; }
    return { x, z, yaw: Math.atan2(-dz, dx) };
  } };
}

/* ======================================================================
   WORLD
   ====================================================================== */
const ROAD_IN = 6.4, ROAD_OUT = 10.6, BY = 0.22, RY = 0.06;

// slab
{
  const p = prop(0, 0, 0, 0);
  box(p.inner, 26, 1.0, 26, C.ground, 0, -0.5, 0, { r: 0.45 });
  box(p.inner, 25.2, 0.42, 25.2, C.base, 0, -1.12, 0, { r: 0.2, cast: false });
}
// road + markings
{
  const p = prop(0, 0, 0, 0.06);
  box(p.inner, ROAD_OUT * 2, RY, ROAD_OUT * 2, C.road, 0, RY / 2, 0, { r: 0.03, cast: false });
  const h = 8.65, rc = 1.4;
  for (let side = 0; side < 4; side++){
    for (let u = -h + rc + 0.7; u < h - rc - 0.5; u += 1.3){
      const m = box(p.inner, 0.62, 0.02, 0.1, C.line, 0, RY + 0.01, 0, { r: 0.009, cast: false });
      if (side === 0) m.position.set(u, m.position.y, h);
      if (side === 1) { m.position.set(h, m.position.y, u); m.rotation.y = Math.PI / 2; }
      if (side === 2) m.position.set(u, m.position.y, -h);
      if (side === 3) { m.position.set(-h, m.position.y, u); m.rotation.y = Math.PI / 2; }
    }
  }
  // teal bike-lane line
  const bl = 7.3;
  for (const s of [1, -1]){
    box(p.inner, bl * 2 - 1.6, 0.02, 0.07, C.teal, 0, RY + 0.01, s * bl, { r: 0.009, cast: false });
    box(p.inner, 0.07, 0.02, bl * 2 - 1.6, C.teal, s * bl, RY + 0.01, 0, { r: 0.009, cast: false });
  }
  // crosswalks
  for (let z = ROAD_IN + 0.35; z < ROAD_OUT - 0.2; z += 0.62) box(p.inner, 1.4, 0.02, 0.32, C.line, -0.6, RY + 0.012, z, { r: 0.009, cast: false });
  for (let x = ROAD_IN + 0.35; x < ROAD_OUT - 0.2; x += 0.62) box(p.inner, 0.32, 0.02, 1.4, C.line, x, RY + 0.012, -0.6, { r: 0.009, cast: false });
}
// block sidewalk
{
  const p = prop(0, 0, 0, 0.1);
  box(p.inner, ROAD_IN * 2, BY, ROAD_IN * 2, C.walk, 0, BY / 2, 0, { r: 0.08 });
}

/* ---------- window grids (instanced) ---------- */
const _m = new THREE.Matrix4(), _q = new THREE.Quaternion(), _s = new THREE.Vector3(1, 1, 1), _v = new THREE.Vector3();
function windows(parent, { w, d, y0, floors, fh, cols, colsSide, ww = 0.5, wh = 0.62, color = C.glass }){
  const list = [];
  for (let f = 0; f < floors; f++){
    const y = y0 + f * fh;
    for (let c = 0; c < cols; c++) list.push([(c - (cols - 1) / 2) * (w / cols), y, d / 2, 0]);
    for (let c = 0; c < colsSide; c++) list.push([w / 2, y, (c - (colsSide - 1) / 2) * (d / colsSide), Math.PI / 2]);
  }
  const im = new THREE.InstancedMesh(geo(ww, wh, 0.1, 0.035), mat(color, { rough: 0.18, metal: 0.15 }), list.length);
  list.forEach(([x, y, z, ry], i) => {
    _q.setFromAxisAngle(_v.set(0, 1, 0), ry);
    _m.compose(new THREE.Vector3(x, y, z), _q, _s);
    im.setMatrixAt(i, _m);
  });
  im.castShadow = true; im.receiveShadow = true;
  parent.add(im);
  return im;
}

const fans = [], blinkers = [];
function building({ x, z, w, d, h, color, trim, cols, colsSide }){
  const p = prop(x, BY, z);
  const g = p.inner;
  boxB(g, w, h, d, color, 0, 0, 0, { r: 0.14 });
  boxB(g, w + 0.14, 0.18, d + 0.14, trim, 0, h, 0, { r: 0.06 });
  // storefront band
  boxB(g, w * 0.86, 0.72, 0.1, C.glass, 0, 0.18, d / 2, { r: 0.04, rough: 0.2 });
  boxB(g, 0.1, 0.72, d * 0.86, C.glass, w / 2, 0.18, 0, { r: 0.04, rough: 0.2 });
  boxB(g, w + 0.06, 0.12, d + 0.06, trim, 0, 1.05, 0, { r: 0.04 });
  const fh = 1.05, floors = Math.floor((h - 1.6) / fh);
  windows(g, { w, d, y0: 1.75, floors, fh, cols, colsSide });
  return { p, g, h };
}

// Tower (royal blue)
{
  const b = building({ x: -3.0, z: -3.0, w: 5.0, d: 5.0, h: 9.6, color: C.royal, trim: C.royalDeep, cols: 4, colsSide: 4 });
  // water tank
  const tg = new THREE.Group(); tg.position.set(-1.0, b.h + 0.18, -0.8); b.g.add(tg);
  for (const [lx, lz] of [[-0.35, -0.35], [0.35, -0.35], [-0.35, 0.35], [0.35, 0.35]]) boxB(tg, 0.08, 0.5, 0.08, C.navy, lx, 0, lz, { r: 0.02 });
  boxB(tg, 1.0, 0.9, 1.0, C.tealLight, 0, 0.5, 0, { r: 0.3 });
  boxB(tg, 1.08, 0.12, 1.08, C.teal, 0, 1.4, 0, { r: 0.05 });
  // antenna + blinking light
  boxB(b.g, 0.08, 1.8, 0.08, C.navy, 1.2, b.h + 0.18, 1.0, { r: 0.03 });
  const bl = boxB(b.g, 0.2, 0.2, 0.2, C.white, 1.2, b.h + 1.95, 1.0, { r: 0.08, material: new THREE.MeshStandardMaterial({ color: 0xffffff, emissive: 0x7ff3e4, emissiveIntensity: 0 }) });
  blinkers.push(bl);
  boxB(b.g, 1.4, 0.5, 0.9, C.stone, 1.0, b.h + 0.18, -1.2, { r: 0.12 });
}
// Mid-rise (green) with AC fans
{
  const b = building({ x: 3.25, z: -3.2, w: 4.6, d: 4.6, h: 6.1, color: C.green, trim: C.greenDeep, cols: 4, colsSide: 4 });
  for (const [ax, az] of [[-1.0, -0.9], [0.4, -0.9], [-1.0, 0.6]]){
    boxB(b.g, 1.0, 0.5, 1.0, C.stone, ax, b.h + 0.18, az, { r: 0.12 });
    const f = new THREE.Group(); f.position.set(ax, b.h + 0.71, az); b.g.add(f);
    box(f, 0.8, 0.04, 0.14, C.navy, 0, 0, 0, { r: 0.02 });
    box(f, 0.14, 0.04, 0.8, C.navy, 0, 0, 0, { r: 0.02 });
    fans.push(f);
  }
  boxB(b.g, 0.6, 0.9, 0.6, C.white, 1.3, b.h + 0.18, 1.2, { r: 0.12 });
}
// Low-rise (teal) with roof garden
{
  const b = building({ x: -3.2, z: 3.0, w: 4.4, d: 4.4, h: 4.7, color: C.teal, trim: 0x0f877d, cols: 3, colsSide: 3 });
  for (const [gx, gz] of [[-1.2, -1.1], [0, -1.1], [1.2, -1.1], [-1.2, 0.4], [1.2, 0.4]]){
    boxB(b.g, 0.8, 0.3, 0.8, C.white, gx, b.h + 0.18, gz, { r: 0.08 });
    boxB(b.g, 0.62, 0.42, 0.62, pick([C.green, C.greenLight, C.greenDeep]), gx, b.h + 0.42, gz, { r: 0.18 });
  }
}

/* ---------- the coffee shop: cutaway interior ---------- */
const SHOP = { x: 2.7, z: 2.7 };
const steam = [];
let barista;
const IN = { svc0: 0.6, step: 2.5 };       // a customer is served every 2.5 s
const CT = 0.53;                           // counter-top height (local)
const shopG = { customers: [], machineSteam: [], sippers: [], typers: [] };
function cupMesh(parent, x = 0, y = 0, z = 0){
  const c = new THREE.Group(); c.position.set(x, y, z); parent.add(c);
  boxB(c, 0.11, 0.14, 0.11, C.white, 0, 0, 0, { r: 0.035 });
  boxB(c, 0.12, 0.05, 0.12, C.orange, 0, 0.04, 0, { r: 0.02, cast: false });
  boxB(c, 0.12, 0.025, 0.12, C.navy, 0, 0.14, 0, { r: 0.01, cast: false });
  return c;
}
{
  const p = prop(SHOP.x, BY, SHOP.z, 0.22);
  const g = p.inner;
  const s = 3.8, half = s / 2;
  shopG.g = g;
  boxB(g, s + 0.1, 0.12, s + 0.1, C.white, 0, 0, 0, { r: 0.05 });
  // checker floor
  { const n = 8, t = (s - 0.2) / n, list = [];
    for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) if ((i + j) % 2) list.push([-half + 0.1 + t * (i + 0.5), -half + 0.1 + t * (j + 0.5)]);
    const im = new THREE.InstancedMesh(geo(t - 0.01, 0.012, t - 0.01, 0.004), mat(0xe3e8f0), list.length);
    list.forEach(([x, z], i) => { _m.makeTranslation(x, 0.126, z); im.setMatrixAt(i, _m); });
    im.receiveShadow = true; g.add(im); }
  // back walls (cutaway: front two sides open)
  boxB(g, s, 1.55, 0.18, C.white, 0, 0.12, -half + 0.09, { r: 0.05 });
  boxB(g, 0.18, 1.55, s, C.white, -half + 0.09, 0.12, 0, { r: 0.05 });
  boxB(g, s - 0.2, 0.36, 0.04, C.tealLight, 0.1, 0.12, -half + 0.2, { r: 0.015 });
  boxB(g, 0.04, 0.36, s - 0.2, C.tealLight, -half + 0.2, 0.12, 0.1, { r: 0.015 });
  boxB(g, s + 0.06, 0.1, 0.24, C.royal, 0, 1.67, -half + 0.09, { r: 0.04 });
  boxB(g, 0.24, 0.1, s + 0.06, C.royal, -half + 0.09, 1.67, 0, { r: 0.04 });
  // front corner post + header beams
  boxB(g, 0.2, 1.65, 0.2, C.white, half - 0.1, 0.12, half - 0.1, { r: 0.06 });
  boxB(g, 0.12, 0.1, s, C.royal, half - 0.06, 1.67, 0, { r: 0.04 });
  boxB(g, s, 0.1, 0.12, C.royal, 0, 1.67, half - 0.06, { r: 0.04 });
  // orange sign band on the header
  boxB(g, 1.6, 0.16, 0.06, 0, 0.5, 1.47, half - 0.02, { r: 0.04, material: glowLike(C.orange) });
  boxB(g, 0.06, 0.16, 1.6, 0, half - 0.02, 1.47, -0.3, { r: 0.04, material: glowLike(C.orange) });
  // low front walls with planters, leaving the door and the side exit open
  for (const [x0, x1] of [[-0.55, 1.7]]){ const w = x1 - x0; boxB(g, w, 0.28, 0.14, C.white, (x0 + x1) / 2, 0.12, half - 0.08, { r: 0.05 }); boxB(g, w - 0.1, 0.12, 0.1, C.green, (x0 + x1) / 2, 0.4, half - 0.08, { r: 0.05 }); }
  for (const [z0, z1] of [[-1.75, -0.25], [1.05, 1.7]]){ const d = z1 - z0; boxB(g, 0.14, 0.28, d, C.white, half - 0.08, 0.12, (z0 + z1) / 2, { r: 0.05 }); boxB(g, 0.1, 0.12, d - 0.1, C.green, half - 0.08, 0.4, (z0 + z1) / 2, { r: 0.05 }); }
  // door frame
  for (const x of [-1.62, -0.78]) boxB(g, 0.08, 1.4, 0.12, C.teal, x, 0.12, half - 0.06, { r: 0.03 });
  boxB(g, 0.92, 0.1, 0.12, C.teal, -1.2, 1.5, half - 0.06, { r: 0.03 });

  // back counter + espresso station
  boxB(g, 3.0, 0.36, 0.42, C.royal, -0.1, 0.12, -1.47, { r: 0.06 });
  boxB(g, 3.04, 0.05, 0.46, C.white, -0.1, 0.48, -1.47, { r: 0.02 });
  const mach = new THREE.Group(); mach.position.set(-0.55, CT, -1.52); g.add(mach);
  boxB(mach, 0.82, 0.38, 0.36, C.stone, 0, 0, 0, { r: 0.07, metal: 0.4, rough: 0.3 });
  boxB(mach, 0.7, 0.12, 0.02, C.royal, 0, 0.22, 0.18, { r: 0.01 });
  for (const gx of [-0.2, 0.2]){
    boxB(mach, 0.12, 0.06, 0.12, C.navy, gx, 0.14, 0.2, { r: 0.03 });
    box(mach, 0.06, 0.03, 0.22, C.navy, gx, 0.15, 0.36, { r: 0.012 });
    box(mach, 0.04, 0.04, 0.02, 0, gx + 0.07, 0.3, 0.19, { r: 0.012, material: glowLike(C.teal), cast: false });
  }
  boxB(mach, 0.6, 0.03, 0.18, C.navy, 0, 0, 0.26, { r: 0.01 });
  box(mach, 0.03, 0.18, 0.03, C.navy, 0.42, 0.12, 0.2, { r: 0.012 });
  for (const cx of [-0.22, 0, 0.22]) boxB(mach, 0.1, 0.09, 0.1, C.white, cx, 0.38, -0.04, { r: 0.03 });
  // grinder, pitcher, cup stack
  boxB(g, 0.22, 0.3, 0.22, C.navy, 0.25, CT, -1.55, { r: 0.06 });
  boxB(g, 0.2, 0.2, 0.2, C.tealLight, 0.25, CT + 0.3, -1.55, { r: 0.06 });
  boxB(g, 0.14, 0.08, 0.14, C.trunk, 0.25, CT + 0.42, -1.55, { r: 0.04, cast: false });
  boxB(g, 0.1, 0.13, 0.1, C.stone, 0.55, CT, -1.42, { r: 0.03, metal: 0.4, rough: 0.3 });
  for (let i = 0; i < 4; i++) boxB(g, 0.11, 0.07, 0.11, C.white, 0.85, CT + i * 0.07, -1.52, { r: 0.025 });
  boxB(g, 0.34, 0.22, 0.26, C.green, 1.2, CT, -1.52, { r: 0.06 });
  // shelves with beans and jars
  for (const y of [0.98, 1.26]){
    boxB(g, 2.2, 0.04, 0.2, C.white, -0.45, y, -1.68, { r: 0.015 });
    for (let i = 0; i < 7; i++){
      const x = -1.4 + i * 0.32;
      const c = [C.navy, C.orange, C.teal, C.navy, C.green, C.royal, C.tealLight][(i + (y > 1 ? 3 : 0)) % 7];
      boxB(g, 0.16, 0.18 + (i % 3) * 0.03, 0.12, c, x, y + 0.04, -1.68, { r: 0.04 });
    }
  }
  // menu boards (no text: rows of bars + orange price dots)
  for (const mz of [-1.0, -0.05, 0.9]){
    boxB(g, 0.04, 0.5, 0.78, C.navy, -half + 0.2, 0.92, mz, { r: 0.03 });
    for (let r = 0; r < 4; r++){
      box(g, 0.02, 0.035, 0.42 - (r % 2) * 0.12, C.white, -half + 0.23, 1.33 - r * 0.1, mz - 0.1, { r: 0.01, cast: false });
      box(g, 0.02, 0.04, 0.06, 0, -half + 0.23, 1.33 - r * 0.1, mz + 0.28, { r: 0.015, material: glowLike(C.orange), cast: false });
    }
  }
  // front service counter
  boxB(g, 2.5, 0.36, 0.46, C.teal, -0.15, 0.12, -0.55, { r: 0.06 });
  boxB(g, 2.56, 0.05, 0.52, C.white, -0.15, 0.48, -0.55, { r: 0.02 });
  for (let i = 0; i < 6; i++) boxB(g, 0.03, 0.26, 0.02, C.tealLight, -1.25 + i * 0.4, 0.17, -0.3, { r: 0.01, cast: false });
  // register
  boxB(g, 0.26, 0.06, 0.2, C.navy, 0.05, CT, -0.6, { r: 0.03 });
  const screen = box(g, 0.26, 0.17, 0.03, 0, 0.05, CT + 0.17, -0.62, { r: 0.015, material: new THREE.MeshStandardMaterial({ color: 0xc8f4ee, emissive: 0x2ee6d0, emissiveIntensity: 0.4, roughness: 0.3 }) });
  screen.rotation.x = 0.35;
  box(g, 0.1, 0.03, 0.14, C.navy, 0.3, CT + 0.03, -0.4, { r: 0.012 });
  shopG.screen = screen;
  // pastry case
  { const pc = new THREE.Group(); pc.position.set(-0.85, CT, -0.55); g.add(pc);
    for (const py of [0.03, 0.16]) for (let i = 0; i < 4; i++)
      boxB(pc, 0.12, 0.06, 0.09, i % 2 ? 0xf2b56b : 0xe08b3c, -0.24 + i * 0.16, py, (i % 2) * 0.06 - 0.03, { r: 0.03 });
    boxB(pc, 0.7, 0.01, 0.36, C.white, 0, 0.13, 0, { r: 0.004, cast: false });
    boxB(pc, 0.72, 0.32, 0.4, 0, 0, 0, 0, { r: 0.04, material: mat(C.tealLight, { rough: 0.1, opacity: 0.3 }), cast: false }); }
  // pickup mat + tip jar
  boxB(g, 0.3, 0.012, 0.22, C.orange, 0.8, CT, -0.5, { r: 0.004, cast: false });
  boxB(g, 0.1, 0.14, 0.1, C.glass, 1.0, CT, -0.62, { r: 0.03, rough: 0.1 });
  // barista
  { const pr = person(C.white, { apron: true });
    pr.g.scale.setScalar(0.85); pr.g.position.set(0.05, 0.12, -1.02);
    g.add(pr.g); barista = pr;
    pr.cup = cupMesh(pr.arms[0], 0, -0.36, 0); }
  shopG.brewCup = cupMesh(g, -0.55, CT, -1.24);
  shopG.pickCup = cupMesh(g, 0.8, CT + 0.012, -0.5);
  // espresso steam
  for (let i = 0; i < 5; i++){
    const m = new THREE.Mesh(geo(0.14, 0.14, 0.14, 0.06), new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.95, transparent: true, opacity: 0, depthWrite: false }));
    g.add(m); shopG.machineSteam.push({ m, phase: i / 5 });
  }
  // café tables with seated customers
  const seat = (x, z, yaw, shirt, laptop) => {
    boxB(g, 0.28, 0.26, 0.28, C.royal, x, 0.12, z, { r: 0.06 });
    const pr = person(shirt);
    pr.g.scale.setScalar(0.82); pr.g.position.set(x, 0.17, z); pr.g.rotation.y = yaw;
    pr.legs.forEach(l => (l.rotation.z = Math.PI / 2.2));
    g.add(pr.g);
    if (laptop){ shopG.typers.push(pr); }
    else { const c = cupMesh(pr.arms[0], 0, -0.34, 0); shopG.sippers.push({ pr, ph: shopG.sippers.length * 0.37 }); }
  };
  const table = (x, z) => {
    boxB(g, 0.06, 0.36, 0.06, C.navy, x, 0.12, z, { r: 0.02 });
    boxB(g, 0.24, 0.03, 0.24, C.navy, x, 0.12, z, { r: 0.01 });
    boxB(g, 0.56, 0.04, 0.56, C.white, x, 0.48, z, { r: 0.02 });
  };
  table(1.25, 1.25);
  seat(1.25, 0.82, Math.PI / 2, C.green); seat(1.25, 1.68, -Math.PI / 2, C.royalDeep);
  cupMesh(g, 1.32, 0.52, 1.18);
  table(0.2, 1.3);
  seat(-0.25, 1.3, 0, C.tealLight, true);
  { const lp = new THREE.Group(); lp.position.set(0.15, 0.52, 1.3); g.add(lp);
    boxB(lp, 0.22, 0.015, 0.3, C.navy, 0, 0, 0, { r: 0.006 });
    const scr = box(lp, 0.015, 0.2, 0.3, 0, 0.1, 0.1, 0, { r: 0.006, material: new THREE.MeshStandardMaterial({ color: 0x2a3566, emissive: 0x2ee6d0, emissiveIntensity: 0.25 }) });
    scr.rotation.z = -0.25; }
  boxB(g, 0.36, 0.3, 0.36, C.white, -1.55, 0.12, 1.5, { r: 0.08 });
  boxB(g, 0.42, 0.55, 0.42, C.green, -1.55, 0.42, 1.5, { r: 0.18 });
  boxB(g, 0.28, 0.32, 0.28, C.greenDeep, -1.5, 0.9, 1.45, { r: 0.12 });
  // queued customers
  const shirtsIn = [C.royal, C.green, C.navy, C.tealLight];
  for (let k = 0; k < 4; k++){
    const pr = person(shirtsIn[k]);
    pr.g.scale.setScalar(0.85);
    g.add(pr.g);
    pr.cup = cupMesh(pr.arms[0], 0, -0.34, 0);
    shopG.customers.push({ pr, s: IN.svc0 + k * IN.step });
  }
}
function glowLike(color){ return new THREE.MeshStandardMaterial({ color, emissive: color, emissiveIntensity: 0.25, roughness: 0.5 }); }

// customer path inside the shop (local coords), times relative to their order moment
const CK = [
  [-3.4, -1.2, 3.3], [-2.2, -1.2, 1.3], [-1.5, -0.55, 0.45], [-0.45, -0.55, 0.45],
  [0.0, 0.05, -0.02], [0.7, 0.05, -0.02], [1.2, 0.8, -0.02], [2.45, 0.8, -0.02],
  [3.1, 1.55, 0.35], [4.1, 3.2, 0.35]
];
// barista keyframes over one 2.5 s service: [time, x, yaw]
const BK = [
  [0.0, 0.05, -Math.PI / 2], [0.7, 0.05, -Math.PI / 2], [0.8, 0.0, -Math.PI], [1.0, -0.55, -1.5 * Math.PI],
  [1.7, -0.55, -1.5 * Math.PI], [1.8, -0.45, -2 * Math.PI], [2.0, 0.8, -2.5 * Math.PI], [2.2, 0.8, -2.5 * Math.PI],
  [2.3, 0.7, -3 * Math.PI], [2.5, 0.05, -2.5 * Math.PI]
];
function keyAt(keys, t){
  if (t <= keys[0][0]) return { v: keys[0], a: keys[0], b: keys[0], f: 0 };
  for (let i = 0; i < keys.length - 1; i++){
    const a = keys[i], b = keys[i + 1];
    if (t <= b[0]){ const f = smooth((t - a[0]) / (b[0] - a[0])); return { v: a.map((x, j) => x + (b[j] - x) * f), a, b, f }; }
  }
  const l = keys[keys.length - 1]; return { v: l, a: l, b: l, f: 1 };
}
function animateShop(lt){
  const tau = mod(lt - IN.svc0, IN.step);
  // barista
  const k = keyAt(BK, tau), x = k.v[1], yaw = k.v[2];
  barista.g.position.x = x;
  barista.g.rotation.y = yaw;
  const walking = Math.abs(k.b[1] - k.a[1]) > 0.05 && k.f > 0 && k.f < 1;
  const sw = walking ? Math.sin(lt * 26) * 0.5 : 0;
  barista.legs[0].rotation.z = sw; barista.legs[1].rotation.z = -sw;
  barista.g.position.y = 0.12 + (walking ? Math.abs(Math.sin(lt * 26)) * 0.03 : 0);
  let a0 = -sw * 0.5, a1 = sw * 0.5;
  if (tau < 0.7){ a0 = 1.2 + 0.12 * Math.sin(lt * 30); a1 = 1.2 + 0.12 * Math.sin(lt * 30 + 1.6); }
  else if (tau >= 1.0 && tau < 1.7){ a0 = 1.35 + 0.1 * Math.sin(lt * 9); a1 = 1.1 + 0.15 * Math.sin(lt * 7); }
  if (tau >= 1.7 && tau < 2.15) a0 = 1.25;
  barista.arms[0].rotation.z = a0; barista.arms[1].rotation.z = a1;
  barista.cup.visible = tau >= 1.7 && tau < 2.1;
  shopG.brewCup.visible = tau >= 1.05 && tau < 1.7;
  shopG.pickCup.visible = tau >= 2.1 && tau < 2.4;
  shopG.screen.material.emissiveIntensity = tau < 0.7 ? 0.9 + 0.3 * Math.sin(lt * 20) : 0.4;
  // espresso steam while the shot pulls
  const brewing = tau >= 1.0 && tau < 1.75 ? 1 : 0;
  for (const st of shopG.machineSteam){
    const u = mod(lt * 1.6 + st.phase, 1);
    st.m.position.set(-0.13 + Math.sin(u * 6 + st.phase * 9) * 0.04, CT + 0.25 + u * 0.55, -1.32 + Math.cos(u * 5) * 0.03);
    st.m.scale.setScalar(0.5 + u * 1.2);
    st.m.material.opacity = brewing * 0.75 * Math.sin(u * Math.PI);
  }
  // customers
  for (const c of shopG.customers){
    let r = mod(lt - c.s, LOOP); if (r > 5) r -= LOOP;   // relative time in [-5, 5)
    const pr = c.pr;
    const vis = r > -3.4 && r < 4.1;
    pr.g.visible = vis;
    if (!vis) continue;
    const kk = keyAt(CK, r);
    pr.g.position.set(kk.v[1], 0.12, kk.v[2]);
    const dx = kk.b[1] - kk.a[1], dz = kk.b[2] - kk.a[2];
    const moving = Math.hypot(dx, dz) > 0.05 && kk.f > 0 && kk.f < 1;
    pr.g.rotation.y = moving ? Math.atan2(-dz, dx) : Math.PI / 2;
    if (r > 2.45 && !moving) pr.g.rotation.y = 0;
    const sc = Math.min(smooth((r + 3.4) / 0.4), 1 - smooth((r - 3.7) / 0.4));
    pr.g.scale.setScalar(Math.max(0.001, 0.85 * sc));
    const w = moving ? Math.sin(lt * 22 + c.s) * 0.5 : 0;
    pr.legs[0].rotation.z = w; pr.legs[1].rotation.z = -w;
    pr.g.position.y = 0.12 + (moving ? Math.abs(Math.sin(lt * 22 + c.s)) * 0.03 : 0);
    const hasCup = r >= 2.4;
    pr.cup.visible = hasCup;
    pr.arms[0].rotation.z = hasCup ? 0.9 : (r >= 0.2 && r < 0.6 ? 0.9 + 0.2 * Math.sin(lt * 18) : -w * 0.5);
    pr.arms[1].rotation.z = w * 0.5;
  }
  for (const sp of shopG.sippers){
    const u = mod(lt / 5 + sp.ph, 1);
    sp.pr.arms[0].rotation.z = 1.9 * smooth(u / 0.2) * (1 - smooth((u - 0.45) / 0.2));
  }
  for (const ty of shopG.typers){
    ty.arms[0].rotation.z = 1.25 + 0.1 * Math.sin(lt * 31);
    ty.arms[1].rotation.z = 1.25 + 0.1 * Math.sin(lt * 29 + 1);
  }
}

/* ---------- people ---------- */
function person(shirt, o = {}){
  const g = new THREE.Group();
  const skin = o.skin ?? pick(C.skin), pants = o.pants ?? pick([C.navy, 0x3a4566, 0x5d6a86]), hair = pick(C.hair);
  const legs = [];
  for (const sz of [-0.075, 0.075]){
    const lg = new THREE.Group(); lg.position.set(0, 0.34, sz);
    box(lg, 0.12, 0.34, 0.11, pants, 0, -0.17, 0, { r: 0.04 });
    g.add(lg); legs.push(lg);
  }
  box(g, 0.22, 0.38, 0.32, shirt, 0, 0.53, 0, { r: 0.08 });
  if (o.apron) box(g, 0.04, 0.3, 0.26, C.orange, 0.12, 0.5, 0, { r: 0.015 });
  const arms = [];
  for (const sz of [-0.2, 0.2]){
    const ag = new THREE.Group(); ag.position.set(0, 0.68, sz);
    box(ag, 0.1, 0.3, 0.08, shirt, 0, -0.14, 0, { r: 0.035 });
    g.add(ag); arms.push(ag);
  }
  box(g, 0.2, 0.2, 0.2, skin, 0, 0.84, 0, { r: 0.07 });
  box(g, 0.22, 0.08, 0.22, hair, -0.01, 0.96, 0, { r: 0.035 });
  return { g, legs, arms };
}
const shirts = [C.royal, C.teal, C.green, C.white, C.navy, C.tealLight, C.greenLight, C.royalDeep];

// queue path (world coords on block sidewalk)
const QP = [[6.05, 6.15], [5.6, 5.3], [4.9, 5.3], [4.2, 5.3], [3.5, 5.3], [2.8, 5.3], [2.15, 5.25], [1.5, 4.75], [1.5, 4.75]];
const QN = 8, STEP = IN.step;
const queue = [];
for (let k = 0; k < 0; k++){
  const p = prop(QP[k][0], BY, QP[k][1]);
  const pr = person(shirts[k % shirts.length]);
  pr.g.scale.setScalar(0.85);
  p.inner.add(pr.g);
  // a few carry an orange cup
  queue.push({ p, pr, k });
}

// café tables with sipping customers on the side sidewalk
const sippers = [];
for (const [tx, tz, ph] of []){
  const p = prop(tx, BY, tz);
  const g = p.inner;
  boxB(g, 0.08, 1.4, 0.08, C.navy, 0, 0, 0, { r: 0.03 });
  const um = boxB(g, 1.5, 0.1, 1.5, C.orange, 0, 1.4, 0, { r: 0.05 });
  boxB(g, 0.7, 0.06, 0.7, C.white, 0, 0.5, 0, { r: 0.03 });
  boxB(g, 0.06, 0.5, 0.06, C.navy, 0, 0, 0, { r: 0.02 });
  boxB(g, 0.16, 0.16, 0.16, C.white, 0.12, 0.56, 0.12, { r: 0.04 });
  for (const sz of [-0.55, 0.55]){
    boxB(g, 0.36, 0.3, 0.36, C.teal, 0, 0, sz, { r: 0.06 });
    const pr = person(pick(shirts));
    pr.g.scale.setScalar(0.82);
    pr.g.position.set(0, 0.06, sz);
    pr.g.rotation.y = sz > 0 ? Math.PI / 2 : -Math.PI / 2;
    pr.legs.forEach(l => (l.rotation.z = Math.PI / 2.2));
    g.add(pr.g);
    const cupM = box(pr.arms[0], 0.12, 0.14, 0.12, C.white, 0, -0.3, 0, { r: 0.04 });
    box(cupM, 0.13, 0.05, 0.13, C.orange, 0, 0, 0, { r: 0.02 });
    sippers.push({ pr, ph: ph + (sz > 0 ? 0.25 : 0) });
  }
}

/* ---------- vehicles ---------- */
function wheel(parent, x, y, z, r, side){
  const w = new THREE.Group(); w.position.set(x, y, z); parent.add(w);
  box(w, r * 2, r * 2, 0.14, C.tire, 0, 0, 0, { r: r * 0.45 });
  box(w, r * 0.9, r * 0.9, 0.04, C.stone, 0, 0, side * 0.07, { r: 0.02 });
  return w;
}
function car(color){
  const g = new THREE.Group(), wheels = [];
  box(g, 1.5, 0.4, 0.82, color, 0, 0.38, 0, { r: 0.15 });
  box(g, 0.86, 0.34, 0.74, C.glass, -0.1, 0.72, 0, { r: 0.12, rough: 0.18, metal: 0.1 });
  box(g, 0.82, 0.07, 0.72, color, -0.1, 0.9, 0, { r: 0.03 });
  for (const s of [-0.26, 0.26]){
    box(g, 0.05, 0.09, 0.16, C.white, 0.75, 0.42, s, { r: 0.02, emissive: 0xfff3d6, ei: 0.5, cast: false });
    box(g, 0.05, 0.09, 0.16, C.navy, -0.75, 0.42, s, { r: 0.02, cast: false });
  }
  for (const wx of [-0.48, 0.48]) for (const wz of [-0.38, 0.38]) wheels.push(wheel(g, wx, 0.17, wz, 0.17, Math.sign(wz)));
  return { g, wheels, r: 0.17 };
}
function bus(color){
  const g = new THREE.Group(), wheels = [];
  box(g, 3.0, 0.95, 0.95, color, 0, 0.66, 0, { r: 0.18 });
  box(g, 2.7, 0.34, 0.98, C.glass, -0.05, 0.86, 0, { r: 0.08, rough: 0.18 });
  box(g, 0.06, 0.5, 0.8, C.glass, 1.49, 0.8, 0, { r: 0.03, rough: 0.18 });
  box(g, 2.9, 0.08, 0.9, C.white, 0, 1.16, 0, { r: 0.03 });
  box(g, 0.8, 0.18, 0.6, C.white, -0.4, 1.28, 0, { r: 0.06 });
  for (const wx of [-1.0, 1.0]) for (const wz of [-0.44, 0.44]) wheels.push(wheel(g, wx, 0.2, wz, 0.2, Math.sign(wz)));
  return { g, wheels, r: 0.2 };
}
function scooter(){
  const g = new THREE.Group(), wheels = [];
  box(g, 0.66, 0.16, 0.26, C.white, 0, 0.3, 0, { r: 0.06 });
  box(g, 0.24, 0.24, 0.26, C.teal, 0.26, 0.42, 0, { r: 0.07 });
  box(g, 0.07, 0.42, 0.07, C.navy, 0.34, 0.6, 0, { r: 0.025 });
  box(g, 0.06, 0.05, 0.42, C.navy, 0.34, 0.82, 0, { r: 0.02 });
  box(g, 0.3, 0.08, 0.24, C.navy, -0.1, 0.44, 0, { r: 0.03 });
  box(g, 0.38, 0.36, 0.38, C.orange, -0.34, 0.68, 0, { r: 0.07, emissive: C.orange, ei: 0.08 });
  // rider
  box(g, 0.22, 0.36, 0.3, C.royal, -0.04, 0.68, 0, { r: 0.08 });
  for (const sz of [-0.13, 0.13]){ const a = box(g, 0.34, 0.08, 0.08, C.royal, 0.14, 0.76, sz, { r: 0.03 }); a.rotation.z = -0.4; }
  box(g, 0.2, 0.18, 0.2, pick(C.skin), -0.02, 0.96, 0, { r: 0.07 });
  box(g, 0.26, 0.14, 0.26, C.teal, -0.03, 1.08, 0, { r: 0.1 });
  for (const wx of [-0.3, 0.32]) wheels.push(wheel(g, wx, 0.14, 0, 0.14, 1));
  return { g, wheels, r: 0.14 };
}

const innerLane = makePath(7.75, 1.4), outerLane = makePath(9.55, 1.8), bikeLane = makePath(6.88, 1.0);
const vehicles = [];
function addVehicle(v, path, rev, offset){
  const p = prop(0, RY, 0);
  p.inner.add(v.g);
  vehicles.push({ ...v, p, path, rev, offset, K: Math.max(1, Math.round(path.L / (TAU * v.r))) });
}
[C.royal, C.white, C.teal].forEach((c, i) => addVehicle(car(c), innerLane, false, i * innerLane.L / 3 + 3));
addVehicle(bus(C.green), outerLane, true, 0);
[C.royalDeep, C.tealLight].forEach((c, i) => addVehicle(car(c), outerLane, true, (i + 1) * outerLane.L / 3));

// scooters parked at the shop curb, leave on a delivery lap and come back
const k0 = 6.88 - 1.0;
const scooters = [
  { s0: 4.25 + k0, dep: 1.5, dur: 7.0 },
  { s0: 3.35 + k0, dep: 3.0, dur: 7.0 }
].map(sc => {
  const v = scooter();
  const p = prop(0, RY, 0);
  p.inner.add(v.g);
  return { ...sc, ...v, p, K: Math.round(bikeLane.L / (TAU * v.r)) };
});

/* ---------- street furniture ---------- */
const trees = [];
function tree(x, z, y = 0, size = 1){
  const p = prop(x, y, z);
  const g = p.inner; g.scale.setScalar(size);
  boxB(g, 0.5, 0.12, 0.5, C.stone, 0, 0, 0, { r: 0.05 });
  boxB(g, 0.16, 0.8, 0.16, C.trunk, 0, 0.1, 0, { r: 0.05 });
  const fol = new THREE.Group(); fol.position.y = 0.8; g.add(fol);
  const c1 = pick([C.green, C.greenDeep, C.teal]);
  box(fol, 0.95, 0.85, 0.95, c1, 0, 0.42, 0, { r: 0.3 });
  box(fol, 0.66, 0.6, 0.66, pick([C.greenLight, C.green]), 0.08, 1.0, -0.05, { r: 0.22 });
  fol.rotation.y = rnd() * TAU;
  trees.push({ fol, ph: rnd() * TAU });
}
function lamp(x, z, rotY, y = 0){
  const p = prop(x, y, z);
  const g = p.inner; g.rotation.y = rotY;
  boxB(g, 0.28, 0.1, 0.28, C.navy, 0, 0, 0, { r: 0.04 });
  boxB(g, 0.09, 2.3, 0.09, C.navy, 0, 0.05, 0, { r: 0.03 });
  box(g, 0.62, 0.07, 0.07, C.navy, 0.28, 2.32, 0, { r: 0.02 });
  box(g, 0.36, 0.12, 0.22, C.navy, 0.56, 2.26, 0, { r: 0.05 });
  box(g, 0.28, 0.04, 0.16, C.white, 0.56, 2.19, 0, { r: 0.015, emissive: 0xfff1d0, ei: 0.9, cast: false });
}
function bench(x, z, rotY){
  const p = prop(x, 0, z);
  const g = p.inner; g.rotation.y = rotY;
  for (const lx of [-0.4, 0.4]) boxB(g, 0.08, 0.3, 0.34, C.navy, lx, 0, 0, { r: 0.02 });
  boxB(g, 1.1, 0.08, 0.38, C.teal, 0, 0.3, 0, { r: 0.03 });
  boxB(g, 1.1, 0.3, 0.06, C.teal, 0, 0.38, -0.17, { r: 0.03 });
}
function hydrant(x, z, y){
  const p = prop(x, y, z);
  boxB(p.inner, 0.2, 0.36, 0.2, C.royal, 0, 0, 0, { r: 0.07 });
  box(p.inner, 0.32, 0.08, 0.1, C.royal, 0, 0.22, 0, { r: 0.03 });
  boxB(p.inner, 0.24, 0.07, 0.24, C.royalDeep, 0, 0.36, 0, { r: 0.03 });
}
function bin(x, z, y){
  const p = prop(x, y, z);
  boxB(p.inner, 0.3, 0.46, 0.3, C.greenDeep, 0, 0, 0, { r: 0.07 });
  boxB(p.inner, 0.34, 0.06, 0.34, C.navy, 0, 0.46, 0, { r: 0.02 });
}

// outer ring (slab sidewalk between road and edge)
const O = 11.8;
for (const u of [-9.5, -4.5, 1.5, 6.5]){ tree(u, -O); tree(-O, u); }
for (const u of [-8, -2.5]){ tree(u, O, 0, 0.9); tree(O, u, 0, 0.9); }
tree(O, O, 0, 1.1); tree(-O, -O, 0, 1.2); tree(O, -O, 0, 1.05); tree(-O, O, 0, 1.05);
for (const u of [-6.5, 4.0]){ lamp(u, 11.0, Math.PI / 2); lamp(11.0, u, 0); lamp(u, -11.0, -Math.PI / 2); lamp(-11.0, u, Math.PI); }
bench(9.0, 12.2, Math.PI); bench(12.2, 8.5, -Math.PI / 2); bench(-1.5, -12.2, 0);
// inner block sidewalk
lamp(6.0, -1.0, Math.PI, BY); lamp(-1.0, 6.0, -Math.PI / 2, BY); lamp(-6.0, 0.4, 0, BY);
tree(-0.1, 1.7, BY, 0.85); tree(-0.1, 4.4, BY, 0.8); tree(0.3, -5.8, BY, 0.75);
hydrant(6.0, -2.4, BY); bin(0.6, 5.9, BY); bin(6.0, 0.5, BY);

// pedestrians on the outer sidewalk
const walkers = [];
function addWalker(axis, fixed, from, to, shirt, dog){
  const p = prop(0, 0, 0);
  const pr = person(shirt); pr.g.scale.setScalar(0.85); p.inner.add(pr.g);
  let d = null;
  if (dog){
    d = new THREE.Group(); p.inner.add(d);
    box(d, 0.42, 0.2, 0.18, C.white, 0, 0.24, 0, { r: 0.07 });
    box(d, 0.18, 0.18, 0.16, C.white, 0.26, 0.36, 0, { r: 0.06 });
    box(d, 0.06, 0.08, 0.16, C.navy, 0.3, 0.46, 0, { r: 0.02 });
    for (const lx of [-0.14, 0.14]) for (const lz of [-0.06, 0.06]) boxB(d, 0.06, 0.14, 0.06, C.navy, lx, 0, lz, { r: 0.02 });
    box(d, 0.14, 0.04, 0.04, C.white, -0.26, 0.34, 0, { r: 0.015 });
  }
  walkers.push({ p, pr, axis, fixed, from, to, d });
}
addWalker('x', 11.6, -12.4, 12.4, C.royal, true);
addWalker('x', 12.3, 12.4, -12.4, C.green, false);
addWalker('z', 11.7, 12.4, -12.4, C.teal, false);
addWalker('z', 12.35, -12.4, 12.4, C.white, false);

/* ---------- post-processing ---------- */
const rt = new THREE.WebGLRenderTarget(W, H, { type: THREE.HalfFloatType, samples: 4 });
const composer = new EffectComposer(renderer, rt);
composer.setPixelRatio(1);
composer.setSize(W, H);
composer.addPass(new RenderPass(scene, camera));
try {
  const gtao = new GTAOPass(scene, camera, W, H);
  gtao.output = GTAOPass.OUTPUT.Default;
  gtao.blendIntensity = 1.0;
  gtao.updateGtaoMaterial({ radius: 0.3, distanceExponent: 1.4, thickness: 1.2, scale: 1.15, samples: 12, distanceFallOff: 1, screenSpaceRadius: false });
  gtao.updatePdMaterial({ lumaPhi: 10, depthPhi: 2, normalPhi: 3, radius: 6, radiusExponent: 1, rings: 2, samples: 16 });
  composer.addPass(gtao);
} catch (e) { console.warn('GTAO unavailable', e); }
composer.addPass(new OutputPass());

/* ---------- overlay stats ---------- */
const elO = document.getElementById('sOrders'), elR = document.getElementById('sRev'), elD = document.getElementById('sDel'), elDR = document.getElementById('dRev');
const fmtInt = n => n.toLocaleString('en-US');
const price = i => { const x = Math.sin(i * 12.9898) * 43758.5453; return 3.5 + (x - Math.floor(x)) * 6.5; };
let lastOrders = -1, lastDel = -1, revTarget = 6842.5, revShown = 6842.5, revIdx = 0;
function bump(el){ el.classList.remove('bump'); void el.offsetWidth; el.classList.add('bump'); }
function updateStats(t, lt){
  const n = t < IN.svc0 + 0.5 ? 0 : Math.floor((t - IN.svc0 - 0.5) / STEP) + 1;
  while (revIdx < n){ revTarget += price(revIdx++); }
  const orders = 1284 + n;
  if (orders !== lastOrders){ elO.textContent = fmtInt(orders); if (lastOrders >= 0) bump(elO); lastOrders = orders; }
  const del = 212 + 2 * Math.floor(t / LOOP) + (lt >= 1.5) + (lt >= 3.0);
  if (del !== lastDel){ elD.textContent = fmtInt(del); if (lastDel >= 0) bump(elD); lastDel = del; }
  const prev = Math.floor(revShown);
  revShown += (revTarget - revShown) * 0.12;
  if (Math.floor(revShown) !== prev){
    elR.textContent = '$' + fmtInt(Math.floor(revShown));
    elDR.textContent = 'avg ticket $' + (revShown / orders).toFixed(2);
  }
  if (revTarget - revShown > 2 && !elR.classList.contains('bump')) bump(elR);
}

/* ---------- animation ---------- */
let start = null;
const card = document.querySelector('.card');
function restart(){
  start = null; buildDone = false;
  lastOrders = -1; lastDel = -1; revTarget = 6842.5; revShown = 6842.5; revIdx = 0;
  elR.textContent = '$6,842';
  card.style.animation = 'none'; void card.offsetWidth; card.style.animation = '';
}
addEventListener('keydown', e => { if (e.code === 'Space' || e.key === 'r' || e.key === 'R') { e.preventDefault(); restart(); } });
addEventListener('pointerdown', restart);
function frame(now){
  if (start === null) start = now;
  const t = (now - start) / 1000, lt = t % LOOP, ph = lt / LOOP;
  applyBuild(t);

  // camera: eased sway-orbit with gentle push in, period = LOOP
  const az = Math.PI / 4 + 0.22 * Math.sin(ph * TAU);
  const push = (1 - Math.cos(ph * TAU)) / 2;
  const R = 15.5 - 1.5 * push, el = 0.5 + 0.03 * Math.sin(ph * TAU);
  camera.position.set(SHOP.x + Math.sin(az) * Math.cos(el) * R, 0.7 + Math.sin(el) * R, SHOP.z + Math.cos(az) * Math.cos(el) * R);
  camera.lookAt(SHOP.x, 0.7, SHOP.z);

  // cars: one lap per loop
  for (const v of vehicles){
    const pt = v.path.at(v.offset + ph * v.path.L, v.rev);
    v.p.root.position.set(pt.x, RY, pt.z);
    v.p.root.rotation.y = pt.yaw;
    const spin = -ph * TAU * v.K;
    v.wheels.forEach(w => (w.rotation.z = spin));
  }

  // scooters
  for (const sc of scooters){
    const u = smooth((lt - sc.dep) / sc.dur);
    const pt = bikeLane.at(sc.s0 + u * bikeLane.L, false);
    const lean = Math.sin(u * Math.PI);
    sc.p.root.position.set(pt.x, RY, pt.z);
    sc.p.root.rotation.y = pt.yaw;
    sc.g.position.y = 0.03 * lean * Math.abs(Math.sin(lt * 18));
    sc.wheels.forEach(w => (w.rotation.z = -u * TAU * sc.K));
  }

  // queue: every STEP seconds everyone shuffles forward one slot
  const step = Math.floor(lt / STEP), fr = (lt % STEP) / STEP;
  const move = smooth(fr / 0.5);
  for (const q of queue){
    const u = (q.k + step + move) % QN;
    const i = Math.floor(u), f = u - i;
    const a = QP[i], b = QP[i + 1];
    const x = a[0] + (b[0] - a[0]) * f, z = a[1] + (b[1] - a[1]) * f;
    q.p.root.position.set(x, BY, z);
    const dx = b[0] - a[0], dz = b[1] - a[1];
    if (Math.hypot(dx, dz) > 0.01) q.p.root.rotation.y = Math.atan2(-dz, dx);
    let s = 1;
    if (u < 1) s = smooth(u * 1.4);
    else if (u >= 6) s = 1 - smooth((u - 6) / 0.9);
    q.pr.g.scale.setScalar(Math.max(0.001, 0.85 * s));
    q.pr.g.visible = s > 0.01;
    const moving = fr < 0.5 ? Math.sin(fr / 0.5 * Math.PI) : 0;
    const sw = Math.sin(lt * 14 + q.k) * 0.55 * moving;
    q.pr.legs[0].rotation.z = sw; q.pr.legs[1].rotation.z = -sw;
    q.pr.g.position.y = Math.abs(Math.sin(lt * 14 + q.k)) * 0.04 * moving;
  }

  // walkers along the outer sidewalk
  for (const w of walkers){
    const v = w.from + (w.to - w.from) * ph;
    const dir = Math.sign(w.to - w.from);
    if (w.axis === 'x'){ w.p.root.position.set(v, 0, w.fixed); w.p.root.rotation.y = dir > 0 ? 0 : Math.PI; }
    else { w.p.root.position.set(w.fixed, 0, v); w.p.root.rotation.y = dir > 0 ? -Math.PI / 2 : Math.PI / 2; }
    const edge = Math.min(Math.abs(v - w.from), Math.abs(v - w.to));
    const s = smooth(edge / 0.8);
    w.p.root.scale.setScalar(Math.max(0.001, s));
    const sw = Math.sin(ph * TAU * 14) * 0.55;
    w.pr.legs[0].rotation.z = sw; w.pr.legs[1].rotation.z = -sw;
    w.pr.arms[0].rotation.z = -sw * 0.6; w.pr.arms[1].rotation.z = sw * 0.6;
    w.pr.g.position.y = Math.abs(Math.sin(ph * TAU * 14)) * 0.035;
    if (w.d){ w.d.position.set(0.75, Math.abs(Math.sin(ph * TAU * 28)) * 0.05, 0.35); }
  }

  // ambient motion
  for (const tr of trees){ tr.fol.rotation.z = 0.035 * Math.sin(ph * TAU * 2 + tr.ph); tr.fol.rotation.x = 0.025 * Math.cos(ph * TAU * 2 + tr.ph); }
  fans.forEach((f, i) => (f.rotation.y = ph * TAU * (6 + i)));
  blinkers.forEach(b => (b.material.emissiveIntensity = (lt % 1) < 0.35 ? 2.2 : 0));
  for (const st of steam){
    const u = (ph * 4 + st.phase) % 1;
    st.m.position.set(Math.sin(u * TAU + st.phase * 9) * 0.14, 1.25 + u * 1.7, Math.cos(u * 5 + st.phase * 4) * 0.12);
    st.m.scale.setScalar(0.35 + u * 1.1);
    st.m.material.opacity = 0.85 * Math.sin(u * Math.PI);
    st.m.rotation.y = u * 2;
  }
  for (const sp of sippers){
    const u = (ph * 2 + sp.ph) % 1;
    const lift = smooth(u / 0.2) * (1 - smooth((u - 0.45) / 0.2));
    sp.pr.arms[0].rotation.z = 1.9 * lift;
    sp.pr.g.position.y = 0.06;
  }
  animateShop(lt);

  updateStats(t, lt);
  composer.render();
  requestAnimationFrame(frame);
}
window.__sceneOK = true;
requestAnimationFrame(frame);
</script>
</body>
</html>
canh-3d-video-doc/03-xuyen-mai-quan-ca-phe.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
</head>
<body>
<title>Daily Grind Xuyên Mái</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,800&family=Manrope:wght@500;600;700;800&display=swap">
<style>
/* Layout: fixed 1088x1920 frame scaled to fit the window; frosted card floats over the top third, diorama sits low. */
:root{
  --bg:#e9ecf1;
  --frame:#f6f7f9;
  --ink:#141b38;
  --muted:#5a6383;
  --accent:#ff7a1c;
  --royal:#2f55e6;
  --teal:#17a99c;
  --green:#3db86a;
  --f-display:'Bricolage Grotesque','Manrope',system-ui,sans-serif;
  --f-body:'Manrope',system-ui,-apple-system,'Segoe UI',sans-serif;
  color-scheme:light;
}
html,body{height:100%;margin:0;overflow:hidden;background:var(--bg);color:var(--ink)}
#stage{
  position:absolute;left:50%;top:50%;
  width:1088px;height:1920px;
  transform:translate(-50%,-50%) scale(var(--s,0.4));
  transform-origin:center center;
  overflow:hidden;background:var(--frame);
}
#c{position:absolute;inset:0;display:block;width:1088px;height:1920px}
.vignette{position:absolute;inset:0;pointer-events:none;
  background:radial-gradient(120% 80% at 50% 60%, rgba(255,255,255,0) 55%, rgba(20,27,56,.07) 100%)}

.card{
  position:absolute;left:84px;right:84px;top:132px;
  padding:42px 48px 44px;
  border-radius:44px;
  background:linear-gradient(160deg, rgba(255,255,255,.62), rgba(255,255,255,.34));
  -webkit-backdrop-filter:blur(26px) saturate(1.5);
  backdrop-filter:blur(26px) saturate(1.5);
  border:1.5px solid rgba(255,255,255,.85);
  box-shadow:0 30px 80px -30px rgba(20,27,56,.35), inset 0 1px 0 rgba(255,255,255,.9);
  font-family:var(--f-body);
  opacity:0;transform:translateY(-24px) scale(.98);
  animation:cardIn .7s cubic-bezier(.2,.9,.25,1.15) .55s forwards;
}
@keyframes cardIn{to{opacity:1;transform:none}}
.head{display:flex;align-items:center;justify-content:space-between;gap:24px}
.brand{display:flex;align-items:center;gap:22px}
.mark{width:68px;height:68px;border-radius:22px;background:var(--accent);position:relative;
  box-shadow:0 10px 24px -8px rgba(255,122,28,.7)}
.mark::before{content:"";position:absolute;left:18px;top:22px;width:26px;height:28px;border-radius:5px 5px 10px 10px;background:#fff}
.mark::after{content:"";position:absolute;left:42px;top:27px;width:9px;height:13px;border:4px solid #fff;border-left:0;border-radius:0 8px 8px 0}
h1{margin:0;font-family:var(--f-display);font-weight:800;font-size:56px;line-height:1;letter-spacing:-.02em;text-wrap:balance}
h1 span{color:var(--muted);font-weight:600}
.sub{margin:10px 0 0;font-size:22px;font-weight:600;color:var(--muted);letter-spacing:.01em}
.live{display:flex;align-items:center;gap:12px;padding:12px 20px;border-radius:999px;
  background:rgba(20,27,56,.9);color:#fff;font-weight:800;font-size:20px;letter-spacing:.16em}
.live i{width:14px;height:14px;border-radius:50%;background:var(--accent);box-shadow:0 0 0 0 rgba(255,122,28,.7);animation:pulse 1s ease-out infinite}
@keyframes pulse{0%{box-shadow:0 0 0 0 rgba(255,122,28,.75)}100%{box-shadow:0 0 0 16px rgba(255,122,28,0)}}
.stats{display:grid;grid-template-columns:1fr 1.25fr 1fr;gap:0;margin-top:36px;
  border-top:1.5px solid rgba(20,27,56,.09)}
.stat{padding:30px 0 0 28px;display:flex;flex-direction:column;gap:10px;min-width:0;border-left:1.5px solid rgba(20,27,56,.09)}
.stat:first-child{padding-left:0;border-left:0}
.label{font-size:19px;font-weight:800;text-transform:uppercase;letter-spacing:.14em;color:var(--muted);display:flex;align-items:center;gap:10px}
.label b{width:12px;height:12px;border-radius:4px;display:inline-block}
.val{font-family:var(--f-body);font-weight:800;font-size:66px;line-height:1;letter-spacing:-.03em;
  font-variant-numeric:tabular-nums;color:var(--ink);display:inline-block;transform-origin:left bottom}
.val.bump{animation:bump .55s ease-out}
@keyframes bump{0%{color:var(--accent);transform:translateY(-6px) scale(1.04)}100%{color:var(--ink);transform:none}}
.delta{font-size:20px;font-weight:700;color:var(--teal);font-variant-numeric:tabular-nums}
@media (prefers-reduced-motion: reduce){.card{animation-duration:.01s}.live i{animation:none}}
</style>

<div id="stage">
  <canvas id="c" width="1088" height="1920"></canvas>
  <div class="vignette"></div>
  <section class="card" aria-label="Daily Grind live sales">
    <div class="head">
      <div class="brand">
        <div class="mark" aria-hidden="true"></div>
        <div>
          <h1>Daily Grind <span>· Live Sales</span></h1>
          <p class="sub">5th &amp; Pine corner store · today</p>
        </div>
      </div>
      <div class="live"><i></i>LIVE</div>
    </div>
    <div class="stats">
      <div class="stat">
        <span class="label"><b style="background:var(--royal)"></b>Orders</span>
        <span class="val" id="sOrders">1,284</span>
        <span class="delta" id="dOrders">+48 / hr</span>
      </div>
      <div class="stat">
        <span class="label"><b style="background:var(--accent)"></b>Revenue</span>
        <span class="val" id="sRev">$6,842</span>
        <span class="delta" id="dRev">avg ticket $6.10</span>
      </div>
      <div class="stat">
        <span class="label"><b style="background:var(--green)"></b>Deliveries</span>
        <span class="val" id="sDel">212</span>
        <span class="delta">2 riders out</span>
      </div>
    </div>
  </section>
</div>

<div id="err" hidden style="position:fixed;left:16px;right:16px;bottom:16px;padding:14px 16px;border-radius:12px;background:#141b38;color:#fff;font:600 14px/1.4 Manrope,system-ui,sans-serif;z-index:9"></div>
<script>
(function(){
  var el=document.getElementById('err');
  function show(m){ el.hidden=false; el.textContent='Không chạy được cảnh 3D: '+m; }
  window.addEventListener('error',function(e){ show(e.message||'lỗi tải script'); },true);
  window.addEventListener('unhandledrejection',function(e){ show(String(e.reason&&e.reason.message||e.reason)); });
  setTimeout(function(){ if(!window.__sceneOK) show('thư viện Three.js chưa tải xong sau 15 giây (mạng hoặc CDN bị chặn).'); },15000);
})();
</script>
<script type="importmap">
{ "imports": {
  "three": "https://cdn.jsdelivr.net/npm/three@0.160.0/+esm"
} }
</script>

<script type="module">
import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.160.0/+esm';
import { RoundedBoxGeometry } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/geometries/RoundedBoxGeometry.js/+esm';
import { EffectComposer } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/EffectComposer.js/+esm';
import { RenderPass } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/RenderPass.js/+esm';
import { GTAOPass } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/GTAOPass.js/+esm';
import { OutputPass } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/OutputPass.js/+esm';

const W = 1088, H = 1920, LOOP = 10, TAU = Math.PI * 2;

/* ---------- fit frame to window ---------- */
const stage = document.getElementById('stage');
function fit(){ stage.style.setProperty('--s', Math.min(innerWidth / W, innerHeight / H)); }
addEventListener('resize', fit); fit();

/* ---------- palette ---------- */
const C = {
  ground:0xf7f6f2, base:0x2a48d4, road:0xd2d7e0, walk:0xe6e9ee, line:0xffffff,
  royal:0x2f55e6, royalDeep:0x2340b8, teal:0x17a99c, tealLight:0x93e0d6,
  green:0x3db86a, greenDeep:0x22864a, greenLight:0x92dba6,
  orange:0xff7a1c, white:0xffffff, navy:0x1d2547, tire:0x2b3040, glass:0xcdeef4,
  trunk:0x8d847b, stone:0xc9ced8,
  skin:[0xf2cba8,0xdba57e,0xae7652,0x7d5136], hair:[0x2b2420,0x5a3b25,0x1d2547,0xd9b77a]
};

/* ---------- seeded random ---------- */
function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296}}
const rnd = mulberry32(11);
const pick = arr => arr[Math.floor(rnd() * arr.length)];
const clamp01 = x => Math.min(1, Math.max(0, x));
const smooth = x => { x = clamp01(x); return x * x * (3 - 2 * x); };
const easeOutCubic = x => 1 - Math.pow(1 - x, 3);
const mod = (a, n) => ((a % n) + n) % n;
const easeOutBack = x => { const c1 = 2.1, c3 = c1 + 1; return 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2); };

/* ---------- renderer ---------- */
const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('c'), antialias: true, powerPreference: 'high-performance' });
renderer.setPixelRatio(1);
renderer.setSize(W, H, false);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;

const scene = new THREE.Scene();
scene.background = new THREE.Color(0xf7f8fa);

const camera = new THREE.PerspectiveCamera(32, W / H, 0.4, 320);
camera.setViewOffset(W, H, 0, -300, W, H); // drop the diorama below the card

/* ---------- lights ---------- */
scene.add(new THREE.HemisphereLight(0xeef3ff, 0xd8d3c8, 1.35));
const sun = new THREE.DirectionalLight(0xfff4e6, 2.7);
sun.position.set(-12, 26, 14);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
Object.assign(sun.shadow.camera, { left:-20, right:20, top:20, bottom:-20, near:1, far:80 });
sun.shadow.bias = -0.0004;
sun.shadow.normalBias = 0.025;
sun.shadow.radius = 5;
scene.add(sun);

/* ---------- geometry + material helpers ---------- */
const geoCache = new Map(), matCache = new Map();
function geo(w, h, d, r){
  r = r ?? Math.min(0.14, Math.min(w, h, d) * 0.22);
  r = Math.min(r, Math.min(w, h, d) / 2 - 0.001);
  const k = [w, h, d, r].map(v => v.toFixed(3)).join('|');
  if (!geoCache.has(k)) geoCache.set(k, new RoundedBoxGeometry(w, h, d, 2, r));
  return geoCache.get(k);
}
function mat(color, o = {}){
  const k = [color, o.rough, o.metal, o.emissive, o.ei, o.opacity].join('|');
  if (!matCache.has(k)) matCache.set(k, new THREE.MeshStandardMaterial({
    color, roughness: o.rough ?? 0.62, metalness: o.metal ?? 0,
    emissive: o.emissive ?? 0x000000, emissiveIntensity: o.ei ?? 1,
    transparent: o.opacity !== undefined, opacity: o.opacity ?? 1
  }));
  return matCache.get(k);
}
function box(parent, w, h, d, color, x = 0, y = 0, z = 0, o = {}){
  const m = new THREE.Mesh(geo(w, h, d, o.r), o.material || mat(color, o));
  m.position.set(x, y, z);
  m.castShadow = o.cast !== false;
  m.receiveShadow = true;
  parent.add(m);
  return m;
}
// bottom-aligned box
const boxB = (p, w, h, d, c, x, y, z, o) => box(p, w, h, d, c, x, y + h / 2, z, o);

/* ---------- build-in system ---------- */
const builds = [];
function prop(x, y, z, delay){
  const root = new THREE.Group(); root.position.set(x, y, z);
  const inner = new THREE.Group(); root.add(inner);
  scene.add(root);
  const dist = Math.hypot(x, z);
  builds.push({ inner, delay: delay ?? (0.16 + (dist / 18) * 0.5 + rnd() * 0.12) });
  return { root, inner };
}
let buildDone = false;
function applyBuild(t){
  if (buildDone) return;
  let all = true;
  for (const b of builds){
    const x = clamp01((t - b.delay) / 0.42);
    if (x < 1) all = false;
    b.inner.visible = x > 0;
    b.inner.scale.setScalar(Math.max(0.001, easeOutBack(x)));
    b.inner.position.y = -1.6 * (1 - easeOutCubic(x));
  }
  if (all) buildDone = true;
}

/* ---------- lane path: rounded rectangle, arc-length param ---------- */
function makePath(h, rc){
  const a = 2 * (h - rc), arc = Math.PI * rc / 2, L = 4 * a + 4 * arc, k = h - rc;
  const starts = [[-k, h], [h, k], [k, -h], [-h, -k]];
  const dirs = [[1, 0], [0, -1], [-1, 0], [0, 1]];
  const centers = [[k, k], [k, -k], [-k, -k], [-k, k]];
  const th0 = [Math.PI / 2, 0, -Math.PI / 2, -Math.PI];
  return { L, at(s, rev){
    if (rev) s = L - s;
    s = ((s % L) + L) % L;
    const seg = a + arc, i = Math.min(3, Math.floor(s / seg)), r = s - i * seg;
    let x, z, dx, dz;
    if (r < a){ x = starts[i][0] + dirs[i][0] * r; z = starts[i][1] + dirs[i][1] * r; dx = dirs[i][0]; dz = dirs[i][1]; }
    else { const th = th0[i] - (r - a) / rc; x = centers[i][0] + rc * Math.cos(th); z = centers[i][1] + rc * Math.sin(th); dx = Math.sin(th); dz = -Math.cos(th); }
    if (rev){ dx = -dx; dz = -dz; }
    return { x, z, yaw: Math.atan2(-dz, dx) };
  } };
}

/* ======================================================================
   WORLD
   ====================================================================== */
const ROAD_IN = 6.4, ROAD_OUT = 10.6, BY = 0.22, RY = 0.06;

// slab
{
  const p = prop(0, 0, 0, 0);
  box(p.inner, 26, 1.0, 26, C.ground, 0, -0.5, 0, { r: 0.45 });
  box(p.inner, 25.2, 0.42, 25.2, C.base, 0, -1.12, 0, { r: 0.2, cast: false });
}
// road + markings
{
  const p = prop(0, 0, 0, 0.06);
  box(p.inner, ROAD_OUT * 2, RY, ROAD_OUT * 2, C.road, 0, RY / 2, 0, { r: 0.03, cast: false });
  const h = 8.65, rc = 1.4;
  for (let side = 0; side < 4; side++){
    for (let u = -h + rc + 0.7; u < h - rc - 0.5; u += 1.3){
      const m = box(p.inner, 0.62, 0.02, 0.1, C.line, 0, RY + 0.01, 0, { r: 0.009, cast: false });
      if (side === 0) m.position.set(u, m.position.y, h);
      if (side === 1) { m.position.set(h, m.position.y, u); m.rotation.y = Math.PI / 2; }
      if (side === 2) m.position.set(u, m.position.y, -h);
      if (side === 3) { m.position.set(-h, m.position.y, u); m.rotation.y = Math.PI / 2; }
    }
  }
  // teal bike-lane line
  const bl = 7.3;
  for (const s of [1, -1]){
    box(p.inner, bl * 2 - 1.6, 0.02, 0.07, C.teal, 0, RY + 0.01, s * bl, { r: 0.009, cast: false });
    box(p.inner, 0.07, 0.02, bl * 2 - 1.6, C.teal, s * bl, RY + 0.01, 0, { r: 0.009, cast: false });
  }
  // crosswalks
  for (let z = ROAD_IN + 0.35; z < ROAD_OUT - 0.2; z += 0.62) box(p.inner, 1.4, 0.02, 0.32, C.line, -0.6, RY + 0.012, z, { r: 0.009, cast: false });
  for (let x = ROAD_IN + 0.35; x < ROAD_OUT - 0.2; x += 0.62) box(p.inner, 0.32, 0.02, 1.4, C.line, x, RY + 0.012, -0.6, { r: 0.009, cast: false });
}
// block sidewalk
{
  const p = prop(0, 0, 0, 0.1);
  box(p.inner, ROAD_IN * 2, BY, ROAD_IN * 2, C.walk, 0, BY / 2, 0, { r: 0.08 });
}

/* ---------- window grids (instanced) ---------- */
const _m = new THREE.Matrix4(), _q = new THREE.Quaternion(), _s = new THREE.Vector3(1, 1, 1), _v = new THREE.Vector3();
function windows(parent, { w, d, y0, floors, fh, cols, colsSide, ww = 0.5, wh = 0.62, color = C.glass }){
  const list = [];
  for (let f = 0; f < floors; f++){
    const y = y0 + f * fh;
    for (let c = 0; c < cols; c++) list.push([(c - (cols - 1) / 2) * (w / cols), y, d / 2, 0]);
    for (let c = 0; c < colsSide; c++) list.push([w / 2, y, (c - (colsSide - 1) / 2) * (d / colsSide), Math.PI / 2]);
  }
  const im = new THREE.InstancedMesh(geo(ww, wh, 0.1, 0.035), mat(color, { rough: 0.18, metal: 0.15 }), list.length);
  list.forEach(([x, y, z, ry], i) => {
    _q.setFromAxisAngle(_v.set(0, 1, 0), ry);
    _m.compose(new THREE.Vector3(x, y, z), _q, _s);
    im.setMatrixAt(i, _m);
  });
  im.castShadow = true; im.receiveShadow = true;
  parent.add(im);
  return im;
}

const fans = [], blinkers = [];
function building({ x, z, w, d, h, color, trim, cols, colsSide }){
  const p = prop(x, BY, z);
  const g = p.inner;
  boxB(g, w, h, d, color, 0, 0, 0, { r: 0.14 });
  boxB(g, w + 0.14, 0.18, d + 0.14, trim, 0, h, 0, { r: 0.06 });
  // storefront band
  boxB(g, w * 0.86, 0.72, 0.1, C.glass, 0, 0.18, d / 2, { r: 0.04, rough: 0.2 });
  boxB(g, 0.1, 0.72, d * 0.86, C.glass, w / 2, 0.18, 0, { r: 0.04, rough: 0.2 });
  boxB(g, w + 0.06, 0.12, d + 0.06, trim, 0, 1.05, 0, { r: 0.04 });
  const fh = 1.05, floors = Math.floor((h - 1.6) / fh);
  windows(g, { w, d, y0: 1.75, floors, fh, cols, colsSide });
  return { p, g, h };
}

// Tower (royal blue)
{
  const b = building({ x: -3.0, z: -3.0, w: 5.0, d: 5.0, h: 9.6, color: C.royal, trim: C.royalDeep, cols: 4, colsSide: 4 });
  // water tank
  const tg = new THREE.Group(); tg.position.set(-1.0, b.h + 0.18, -0.8); b.g.add(tg);
  for (const [lx, lz] of [[-0.35, -0.35], [0.35, -0.35], [-0.35, 0.35], [0.35, 0.35]]) boxB(tg, 0.08, 0.5, 0.08, C.navy, lx, 0, lz, { r: 0.02 });
  boxB(tg, 1.0, 0.9, 1.0, C.tealLight, 0, 0.5, 0, { r: 0.3 });
  boxB(tg, 1.08, 0.12, 1.08, C.teal, 0, 1.4, 0, { r: 0.05 });
  // antenna + blinking light
  boxB(b.g, 0.08, 1.8, 0.08, C.navy, 1.2, b.h + 0.18, 1.0, { r: 0.03 });
  const bl = boxB(b.g, 0.2, 0.2, 0.2, C.white, 1.2, b.h + 1.95, 1.0, { r: 0.08, material: new THREE.MeshStandardMaterial({ color: 0xffffff, emissive: 0x7ff3e4, emissiveIntensity: 0 }) });
  blinkers.push(bl);
  boxB(b.g, 1.4, 0.5, 0.9, C.stone, 1.0, b.h + 0.18, -1.2, { r: 0.12 });
}
// Mid-rise (green) with AC fans
{
  const b = building({ x: 3.25, z: -3.2, w: 4.6, d: 4.6, h: 6.1, color: C.green, trim: C.greenDeep, cols: 4, colsSide: 4 });
  for (const [ax, az] of [[-1.0, -0.9], [0.4, -0.9], [-1.0, 0.6]]){
    boxB(b.g, 1.0, 0.5, 1.0, C.stone, ax, b.h + 0.18, az, { r: 0.12 });
    const f = new THREE.Group(); f.position.set(ax, b.h + 0.71, az); b.g.add(f);
    box(f, 0.8, 0.04, 0.14, C.navy, 0, 0, 0, { r: 0.02 });
    box(f, 0.14, 0.04, 0.8, C.navy, 0, 0, 0, { r: 0.02 });
    fans.push(f);
  }
  boxB(b.g, 0.6, 0.9, 0.6, C.white, 1.3, b.h + 0.18, 1.2, { r: 0.12 });
}
// Low-rise (teal) with roof garden
{
  const b = building({ x: -3.2, z: 3.0, w: 4.4, d: 4.4, h: 4.7, color: C.teal, trim: 0x0f877d, cols: 3, colsSide: 3 });
  for (const [gx, gz] of [[-1.2, -1.1], [0, -1.1], [1.2, -1.1], [-1.2, 0.4], [1.2, 0.4]]){
    boxB(b.g, 0.8, 0.3, 0.8, C.white, gx, b.h + 0.18, gz, { r: 0.08 });
    boxB(b.g, 0.62, 0.42, 0.62, pick([C.green, C.greenLight, C.greenDeep]), gx, b.h + 0.42, gz, { r: 0.18 });
  }
}

/* ---------- the coffee shop: cutaway interior ---------- */
const SHOP = { x: 2.7, z: 2.7 };
const steam = [];
let barista;
const IN = { svc0: 0.6, step: 2.5 };       // a customer is served every 2.5 s
const CT = 0.53;                           // counter-top height (local)
const shopG = { customers: [], machineSteam: [], sippers: [], typers: [] };
function cupMesh(parent, x = 0, y = 0, z = 0){
  const c = new THREE.Group(); c.position.set(x, y, z); parent.add(c);
  boxB(c, 0.11, 0.14, 0.11, C.white, 0, 0, 0, { r: 0.035 });
  boxB(c, 0.12, 0.05, 0.12, C.orange, 0, 0.04, 0, { r: 0.02, cast: false });
  boxB(c, 0.12, 0.025, 0.12, C.navy, 0, 0.14, 0, { r: 0.01, cast: false });
  return c;
}
{
  const p = prop(SHOP.x, BY, SHOP.z, 0.22);
  const g = p.inner;
  const s = 3.8, half = s / 2;
  shopG.g = g;
  boxB(g, s + 0.1, 0.12, s + 0.1, C.white, 0, 0, 0, { r: 0.05 });
  // checker floor
  { const n = 8, t = (s - 0.2) / n, list = [];
    for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) if ((i + j) % 2) list.push([-half + 0.1 + t * (i + 0.5), -half + 0.1 + t * (j + 0.5)]);
    const im = new THREE.InstancedMesh(geo(t - 0.01, 0.012, t - 0.01, 0.004), mat(0xe3e8f0), list.length);
    list.forEach(([x, z], i) => { _m.makeTranslation(x, 0.126, z); im.setMatrixAt(i, _m); });
    im.receiveShadow = true; g.add(im); }
  // back walls (cutaway: front two sides open)
  boxB(g, s, 1.55, 0.18, C.white, 0, 0.12, -half + 0.09, { r: 0.05 });
  boxB(g, 0.18, 1.55, s, C.white, -half + 0.09, 0.12, 0, { r: 0.05 });
  boxB(g, s - 0.2, 0.36, 0.04, C.tealLight, 0.1, 0.12, -half + 0.2, { r: 0.015 });
  boxB(g, 0.04, 0.36, s - 0.2, C.tealLight, -half + 0.2, 0.12, 0.1, { r: 0.015 });
  boxB(g, s + 0.06, 0.1, 0.24, C.royal, 0, 1.67, -half + 0.09, { r: 0.04 });
  boxB(g, 0.24, 0.1, s + 0.06, C.royal, -half + 0.09, 1.67, 0, { r: 0.04 });
  // front corner post + header beams
  boxB(g, 0.2, 1.65, 0.2, C.white, half - 0.1, 0.12, half - 0.1, { r: 0.06 });
  boxB(g, 0.12, 0.1, s, C.royal, half - 0.06, 1.67, 0, { r: 0.04 });
  boxB(g, s, 0.1, 0.12, C.royal, 0, 1.67, half - 0.06, { r: 0.04 });
  // orange sign band on the header
  boxB(g, 1.6, 0.16, 0.06, 0, 0.5, 1.47, half - 0.02, { r: 0.04, material: glowLike(C.orange) });
  boxB(g, 0.06, 0.16, 1.6, 0, half - 0.02, 1.47, -0.3, { r: 0.04, material: glowLike(C.orange) });
  // low front walls with planters, leaving the door and the side exit open
  for (const [x0, x1] of [[-0.55, 1.7]]){ const w = x1 - x0; boxB(g, w, 0.28, 0.14, C.white, (x0 + x1) / 2, 0.12, half - 0.08, { r: 0.05 }); boxB(g, w - 0.1, 0.12, 0.1, C.green, (x0 + x1) / 2, 0.4, half - 0.08, { r: 0.05 }); }
  for (const [z0, z1] of [[-1.75, -0.25], [1.05, 1.7]]){ const d = z1 - z0; boxB(g, 0.14, 0.28, d, C.white, half - 0.08, 0.12, (z0 + z1) / 2, { r: 0.05 }); boxB(g, 0.1, 0.12, d - 0.1, C.green, half - 0.08, 0.4, (z0 + z1) / 2, { r: 0.05 }); }
  // door frame
  for (const x of [-1.62, -0.78]) boxB(g, 0.08, 1.4, 0.12, C.teal, x, 0.12, half - 0.06, { r: 0.03 });
  boxB(g, 0.92, 0.1, 0.12, C.teal, -1.2, 1.5, half - 0.06, { r: 0.03 });

  // back counter + espresso station
  boxB(g, 3.0, 0.36, 0.42, C.royal, -0.1, 0.12, -1.47, { r: 0.06 });
  boxB(g, 3.04, 0.05, 0.46, C.white, -0.1, 0.48, -1.47, { r: 0.02 });
  const mach = new THREE.Group(); mach.position.set(-0.55, CT, -1.52); g.add(mach);
  boxB(mach, 0.82, 0.38, 0.36, C.stone, 0, 0, 0, { r: 0.07, metal: 0.4, rough: 0.3 });
  boxB(mach, 0.7, 0.12, 0.02, C.royal, 0, 0.22, 0.18, { r: 0.01 });
  for (const gx of [-0.2, 0.2]){
    boxB(mach, 0.12, 0.06, 0.12, C.navy, gx, 0.14, 0.2, { r: 0.03 });
    box(mach, 0.06, 0.03, 0.22, C.navy, gx, 0.15, 0.36, { r: 0.012 });
    box(mach, 0.04, 0.04, 0.02, 0, gx + 0.07, 0.3, 0.19, { r: 0.012, material: glowLike(C.teal), cast: false });
  }
  boxB(mach, 0.6, 0.03, 0.18, C.navy, 0, 0, 0.26, { r: 0.01 });
  box(mach, 0.03, 0.18, 0.03, C.navy, 0.42, 0.12, 0.2, { r: 0.012 });
  for (const cx of [-0.22, 0, 0.22]) boxB(mach, 0.1, 0.09, 0.1, C.white, cx, 0.38, -0.04, { r: 0.03 });
  // grinder, pitcher, cup stack
  boxB(g, 0.22, 0.3, 0.22, C.navy, 0.25, CT, -1.55, { r: 0.06 });
  boxB(g, 0.2, 0.2, 0.2, C.tealLight, 0.25, CT + 0.3, -1.55, { r: 0.06 });
  boxB(g, 0.14, 0.08, 0.14, C.trunk, 0.25, CT + 0.42, -1.55, { r: 0.04, cast: false });
  boxB(g, 0.1, 0.13, 0.1, C.stone, 0.55, CT, -1.42, { r: 0.03, metal: 0.4, rough: 0.3 });
  for (let i = 0; i < 4; i++) boxB(g, 0.11, 0.07, 0.11, C.white, 0.85, CT + i * 0.07, -1.52, { r: 0.025 });
  boxB(g, 0.34, 0.22, 0.26, C.green, 1.2, CT, -1.52, { r: 0.06 });
  // shelves with beans and jars
  for (const y of [0.98, 1.26]){
    boxB(g, 2.2, 0.04, 0.2, C.white, -0.45, y, -1.68, { r: 0.015 });
    for (let i = 0; i < 7; i++){
      const x = -1.4 + i * 0.32;
      const c = [C.navy, C.orange, C.teal, C.navy, C.green, C.royal, C.tealLight][(i + (y > 1 ? 3 : 0)) % 7];
      boxB(g, 0.16, 0.18 + (i % 3) * 0.03, 0.12, c, x, y + 0.04, -1.68, { r: 0.04 });
    }
  }
  // menu boards (no text: rows of bars + orange price dots)
  for (const mz of [-1.0, -0.05, 0.9]){
    boxB(g, 0.04, 0.5, 0.78, C.navy, -half + 0.2, 0.92, mz, { r: 0.03 });
    for (let r = 0; r < 4; r++){
      box(g, 0.02, 0.035, 0.42 - (r % 2) * 0.12, C.white, -half + 0.23, 1.33 - r * 0.1, mz - 0.1, { r: 0.01, cast: false });
      box(g, 0.02, 0.04, 0.06, 0, -half + 0.23, 1.33 - r * 0.1, mz + 0.28, { r: 0.015, material: glowLike(C.orange), cast: false });
    }
  }
  // front service counter
  boxB(g, 2.5, 0.36, 0.46, C.teal, -0.15, 0.12, -0.55, { r: 0.06 });
  boxB(g, 2.56, 0.05, 0.52, C.white, -0.15, 0.48, -0.55, { r: 0.02 });
  for (let i = 0; i < 6; i++) boxB(g, 0.03, 0.26, 0.02, C.tealLight, -1.25 + i * 0.4, 0.17, -0.3, { r: 0.01, cast: false });
  // register
  boxB(g, 0.26, 0.06, 0.2, C.navy, 0.05, CT, -0.6, { r: 0.03 });
  const screen = box(g, 0.26, 0.17, 0.03, 0, 0.05, CT + 0.17, -0.62, { r: 0.015, material: new THREE.MeshStandardMaterial({ color: 0xc8f4ee, emissive: 0x2ee6d0, emissiveIntensity: 0.4, roughness: 0.3 }) });
  screen.rotation.x = 0.35;
  box(g, 0.1, 0.03, 0.14, C.navy, 0.3, CT + 0.03, -0.4, { r: 0.012 });
  shopG.screen = screen;
  // pastry case
  { const pc = new THREE.Group(); pc.position.set(-0.85, CT, -0.55); g.add(pc);
    for (const py of [0.03, 0.16]) for (let i = 0; i < 4; i++)
      boxB(pc, 0.12, 0.06, 0.09, i % 2 ? 0xf2b56b : 0xe08b3c, -0.24 + i * 0.16, py, (i % 2) * 0.06 - 0.03, { r: 0.03 });
    boxB(pc, 0.7, 0.01, 0.36, C.white, 0, 0.13, 0, { r: 0.004, cast: false });
    boxB(pc, 0.72, 0.32, 0.4, 0, 0, 0, 0, { r: 0.04, material: mat(C.tealLight, { rough: 0.1, opacity: 0.3 }), cast: false }); }
  // pickup mat + tip jar
  boxB(g, 0.3, 0.012, 0.22, C.orange, 0.8, CT, -0.5, { r: 0.004, cast: false });
  boxB(g, 0.1, 0.14, 0.1, C.glass, 1.0, CT, -0.62, { r: 0.03, rough: 0.1 });
  // barista
  { const pr = person(C.white, { apron: true });
    pr.g.scale.setScalar(0.85); pr.g.position.set(0.05, 0.12, -1.02);
    g.add(pr.g); barista = pr;
    pr.cup = cupMesh(pr.arms[0], 0, -0.36, 0); }
  shopG.brewCup = cupMesh(g, -0.55, CT, -1.24);
  shopG.pickCup = cupMesh(g, 0.8, CT + 0.012, -0.5);
  // espresso steam
  for (let i = 0; i < 5; i++){
    const m = new THREE.Mesh(geo(0.14, 0.14, 0.14, 0.06), new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.95, transparent: true, opacity: 0, depthWrite: false }));
    g.add(m); shopG.machineSteam.push({ m, phase: i / 5 });
  }
  // café tables with seated customers
  const seat = (x, z, yaw, shirt, laptop) => {
    boxB(g, 0.28, 0.26, 0.28, C.royal, x, 0.12, z, { r: 0.06 });
    const pr = person(shirt);
    pr.g.scale.setScalar(0.82); pr.g.position.set(x, 0.17, z); pr.g.rotation.y = yaw;
    pr.legs.forEach(l => (l.rotation.z = Math.PI / 2.2));
    g.add(pr.g);
    if (laptop){ shopG.typers.push(pr); }
    else { const c = cupMesh(pr.arms[0], 0, -0.34, 0); shopG.sippers.push({ pr, ph: shopG.sippers.length * 0.37 }); }
  };
  const table = (x, z) => {
    boxB(g, 0.06, 0.36, 0.06, C.navy, x, 0.12, z, { r: 0.02 });
    boxB(g, 0.24, 0.03, 0.24, C.navy, x, 0.12, z, { r: 0.01 });
    boxB(g, 0.56, 0.04, 0.56, C.white, x, 0.48, z, { r: 0.02 });
  };
  table(1.25, 1.25);
  seat(1.25, 0.82, Math.PI / 2, C.green); seat(1.25, 1.68, -Math.PI / 2, C.royalDeep);
  cupMesh(g, 1.32, 0.52, 1.18);
  table(0.2, 1.3);
  seat(-0.25, 1.3, 0, C.tealLight, true);
  { const lp = new THREE.Group(); lp.position.set(0.15, 0.52, 1.3); g.add(lp);
    boxB(lp, 0.22, 0.015, 0.3, C.navy, 0, 0, 0, { r: 0.006 });
    const scr = box(lp, 0.015, 0.2, 0.3, 0, 0.1, 0.1, 0, { r: 0.006, material: new THREE.MeshStandardMaterial({ color: 0x2a3566, emissive: 0x2ee6d0, emissiveIntensity: 0.25 }) });
    scr.rotation.z = -0.25; }
  boxB(g, 0.36, 0.3, 0.36, C.white, -1.55, 0.12, 1.5, { r: 0.08 });
  boxB(g, 0.42, 0.55, 0.42, C.green, -1.55, 0.42, 1.5, { r: 0.18 });
  boxB(g, 0.28, 0.32, 0.28, C.greenDeep, -1.5, 0.9, 1.45, { r: 0.12 });
  // queued customers
  const shirtsIn = [C.royal, C.green, C.navy, C.tealLight];
  for (let k = 0; k < 4; k++){
    const pr = person(shirtsIn[k]);
    pr.g.scale.setScalar(0.85);
    g.add(pr.g);
    pr.cup = cupMesh(pr.arms[0], 0, -0.34, 0);
    shopG.customers.push({ pr, s: IN.svc0 + k * IN.step });
  }
}
function glowLike(color){ return new THREE.MeshStandardMaterial({ color, emissive: color, emissiveIntensity: 0.25, roughness: 0.5 }); }

/* ---------- exterior shell + upper floor ("lid") that blow open during the dive ---------- */
const shell = new THREE.Group(), lid = new THREE.Group();
shopG.g.add(shell); shopG.g.add(lid);
{
  const g = shell, s = 3.8, half = s / 2;
  boxB(g, s - 0.16, 1.3, s - 0.16, C.glass, 0, 0.12, 0, { r: 0.06, rough: 0.12, metal: 0.1, opacity: 0.4, cast: false });
  for (const u of [-0.55, 0.55]){ boxB(g, 0.1, 1.3, 0.1, C.white, u, 0.12, half - 0.05, { r: 0.03 }); boxB(g, 0.1, 1.3, 0.1, C.white, half - 0.05, 0.12, u, { r: 0.03 }); }
  const stripes = 8;
  for (let i = 0; i < stripes; i++){
    const u = -half + 0.24 + i * ((s - 0.48) / (stripes - 1));
    const col = i % 2 ? C.white : C.orange;
    const a = box(g, 0.44, 0.07, 0.9, col, u, 1.36, half + 0.42, { r: 0.03 }); a.rotation.x = 0.36;
    const b = box(g, 0.9, 0.07, 0.44, col, half + 0.42, 1.36, u, { r: 0.03 }); b.rotation.z = -0.36;
  }
}
{
  const g = lid, s = 3.8, half = s / 2;
  boxB(g, s + 0.12, 0.16, s + 0.12, C.white, 0, 1.42, 0, { r: 0.05 });
  boxB(g, s, 1.5, s, C.white, 0, 1.58, 0, { r: 0.12 });
  windows(g, { w: s, d: s, y0: 2.45, floors: 1, fh: 1, cols: 3, colsSide: 3, ww: 0.7, wh: 0.62, color: C.royal });
  boxB(g, s + 0.16, 0.14, s + 0.16, C.tealLight, 0, 3.08, 0, { r: 0.05 });
  boxB(g, 1.9, 0.38, 0.12, C.orange, 0.5, 1.7, half + 0.02, { r: 0.08, emissive: C.orange, ei: 0.12 });
  boxB(g, 0.12, 0.38, 1.9, C.orange, half + 0.02, 1.7, -0.3, { r: 0.08, emissive: C.orange, ei: 0.12 });
  const cup = new THREE.Group(); cup.position.set(0.3, 3.15, -0.2); g.add(cup);
  boxB(cup, 1.0, 1.1, 1.0, C.white, 0, 0, 0, { r: 0.22 });
  boxB(cup, 1.06, 0.3, 1.06, C.orange, 0, 0.38, 0, { r: 0.1 });
  boxB(cup, 1.1, 0.1, 1.1, C.navy, 0, 1.08, 0, { r: 0.04 });
  box(cup, 0.18, 0.5, 0.16, C.white, 0.62, 0.6, 0, { r: 0.07 });
  for (let i = 0; i < 6; i++){
    const m = new THREE.Mesh(geo(0.32, 0.32, 0.32, 0.12), new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.9, transparent: true, opacity: 0.8, depthWrite: false }));
    m.castShadow = false; cup.add(m);
    steam.push({ m, phase: i / 6 });
  }
}
const OPEN = { shell0: 5.7, shell1: 6.3, lid0: 6.0, lid1: 6.9 };
function animateOpen(t){
  // glass + awnings sink away
  const a = clamp01((t - OPEN.shell0) / (OPEN.shell1 - OPEN.shell0));
  shell.visible = a < 1;
  shell.scale.setScalar(Math.max(0.001, 1 - a * a));
  shell.position.y = -0.4 * a;
  // upper floor: small anticipation squash, then pops up and away past the camera
  const b = clamp01((t - OPEN.lid0) / (OPEN.lid1 - OPEN.lid0));
  lid.visible = b < 1;
  const pre = Math.sin(clamp01(b / 0.18) * Math.PI) * 0.06;
  lid.scale.set(1 + pre, 1 - pre, 1 + pre);
  const lift = b < 0.18 ? 0 : Math.pow((b - 0.18) / 0.82, 2);
  lid.position.y = lift * 11;
  lid.rotation.x = lift * 0.5; lid.rotation.z = -lift * 0.35;
  if (b > 0.18) lid.scale.setScalar(Math.max(0.001, 1 - lift * 0.85));
}

/* ---------- one-shot camera: wide build-up -> dive -> close-up ---------- */
// [time, targetX, targetY, targetZ, R, elevation, azimuth, fov, viewOffsetY]
const Q = Math.PI / 4;
const CAMK = [
  [0.0, 0, 1.2, 0, 140, 0.64, Q - 0.30, 32, -190],
  [4.0, 0, 1.2, 0, 122, 0.58, Q + 0.05, 32, -190],
  [5.6, 1.9, 1.0, 1.9, 42, 0.98, Q + 0.18, 34, -230],
  [6.6, 2.7, 0.7, 2.7, 10, 1.30, Q + 0.24, 40, -280],
  [7.4, 2.7, 0.6, 2.7, 6.8, 1.02, Q + 0.14, 45, -300],
  [8.8, 2.7, 0.7, 2.7, 10.5, 0.55, Q, 45, -300]
];
const camLog = CAMK.map(k => k.map((v, j) => (j === 4 ? Math.log(v) : v)));
function camAt(t){
  const K = camLog, n = K.length;
  if (t >= K[n - 1][0]) return K[n - 1].slice();
  let i = 0; while (t > K[i + 1][0]) i++;
  const t0 = K[i][0], t1 = K[i + 1][0], h = t1 - t0, u = (t - t0) / h;
  const h00 = 2*u*u*u - 3*u*u + 1, h10 = u*u*u - 2*u*u + u, h01 = -2*u*u*u + 3*u*u, h11 = u*u*u - u*u;
  const tan = (k, j) => (k === 0 || k === n - 1) ? 0 : (K[k + 1][j] - K[k - 1][j]) / (K[k + 1][0] - K[k - 1][0]);
  const out = [t];
  for (let j = 1; j < K[0].length; j++) out.push(h00 * K[i][j] + h10 * h * tan(i, j) + h01 * K[i + 1][j] + h11 * h * tan(i + 1, j));
  return out;
}
let lastFov = 0, lastOff = 1e9;
function placeCamera(t){
  const c = camAt(t);
  let [, tx, ty, tz, lr, el, az, fov, off] = c;
  let R = Math.exp(lr);
  const end = CAMK[CAMK.length - 1][0];
  if (t > end){ const d = t - end, e = smooth(d / 1.5); az += 0.16 * Math.sin(d * 0.55) * e; R -= 0.8 * (1 - Math.cos(d * 0.5)) * 0.5 * e; }
  camera.position.set(tx + Math.sin(az) * Math.cos(el) * R, ty + Math.sin(el) * R, tz + Math.cos(az) * Math.cos(el) * R);
  camera.lookAt(tx, ty, tz);
  if (Math.abs(fov - lastFov) > 1e-3 || Math.abs(off - lastOff) > 1e-2){
    camera.fov = fov; camera.setViewOffset(W, H, 0, off, W, H); camera.updateProjectionMatrix();
    lastFov = fov; lastOff = off;
  }
}

// customer path inside the shop (local coords), times relative to their order moment
const CK = [
  [-3.4, -1.2, 3.3], [-2.2, -1.2, 1.3], [-1.5, -0.55, 0.45], [-0.45, -0.55, 0.45],
  [0.0, 0.05, -0.02], [0.7, 0.05, -0.02], [1.2, 0.8, -0.02], [2.45, 0.8, -0.02],
  [3.1, 1.55, 0.35], [4.1, 3.2, 0.35]
];
// barista keyframes over one 2.5 s service: [time, x, yaw]
const BK = [
  [0.0, 0.05, -Math.PI / 2], [0.7, 0.05, -Math.PI / 2], [0.8, 0.0, -Math.PI], [1.0, -0.55, -1.5 * Math.PI],
  [1.7, -0.55, -1.5 * Math.PI], [1.8, -0.45, -2 * Math.PI], [2.0, 0.8, -2.5 * Math.PI], [2.2, 0.8, -2.5 * Math.PI],
  [2.3, 0.7, -3 * Math.PI], [2.5, 0.05, -2.5 * Math.PI]
];
function keyAt(keys, t){
  if (t <= keys[0][0]) return { v: keys[0], a: keys[0], b: keys[0], f: 0 };
  for (let i = 0; i < keys.length - 1; i++){
    const a = keys[i], b = keys[i + 1];
    if (t <= b[0]){ const f = smooth((t - a[0]) / (b[0] - a[0])); return { v: a.map((x, j) => x + (b[j] - x) * f), a, b, f }; }
  }
  const l = keys[keys.length - 1]; return { v: l, a: l, b: l, f: 1 };
}
function animateShop(lt){
  const tau = mod(lt - IN.svc0, IN.step);
  // barista
  const k = keyAt(BK, tau), x = k.v[1], yaw = k.v[2];
  barista.g.position.x = x;
  barista.g.rotation.y = yaw;
  const walking = Math.abs(k.b[1] - k.a[1]) > 0.05 && k.f > 0 && k.f < 1;
  const sw = walking ? Math.sin(lt * 26) * 0.5 : 0;
  barista.legs[0].rotation.z = sw; barista.legs[1].rotation.z = -sw;
  barista.g.position.y = 0.12 + (walking ? Math.abs(Math.sin(lt * 26)) * 0.03 : 0);
  let a0 = -sw * 0.5, a1 = sw * 0.5;
  if (tau < 0.7){ a0 = 1.2 + 0.12 * Math.sin(lt * 30); a1 = 1.2 + 0.12 * Math.sin(lt * 30 + 1.6); }
  else if (tau >= 1.0 && tau < 1.7){ a0 = 1.35 + 0.1 * Math.sin(lt * 9); a1 = 1.1 + 0.15 * Math.sin(lt * 7); }
  if (tau >= 1.7 && tau < 2.15) a0 = 1.25;
  barista.arms[0].rotation.z = a0; barista.arms[1].rotation.z = a1;
  barista.cup.visible = tau >= 1.7 && tau < 2.1;
  shopG.brewCup.visible = tau >= 1.05 && tau < 1.7;
  shopG.pickCup.visible = tau >= 2.1 && tau < 2.4;
  shopG.screen.material.emissiveIntensity = tau < 0.7 ? 0.9 + 0.3 * Math.sin(lt * 20) : 0.4;
  // espresso steam while the shot pulls
  const brewing = tau >= 1.0 && tau < 1.75 ? 1 : 0;
  for (const st of shopG.machineSteam){
    const u = mod(lt * 1.6 + st.phase, 1);
    st.m.position.set(-0.13 + Math.sin(u * 6 + st.phase * 9) * 0.04, CT + 0.25 + u * 0.55, -1.32 + Math.cos(u * 5) * 0.03);
    st.m.scale.setScalar(0.5 + u * 1.2);
    st.m.material.opacity = brewing * 0.75 * Math.sin(u * Math.PI);
  }
  // customers
  for (const c of shopG.customers){
    let r = mod(lt - c.s, LOOP); if (r > 5) r -= LOOP;   // relative time in [-5, 5)
    const pr = c.pr;
    const vis = r > -3.4 && r < 4.1;
    pr.g.visible = vis;
    if (!vis) continue;
    const kk = keyAt(CK, r);
    pr.g.position.set(kk.v[1], 0.12, kk.v[2]);
    const dx = kk.b[1] - kk.a[1], dz = kk.b[2] - kk.a[2];
    const moving = Math.hypot(dx, dz) > 0.05 && kk.f > 0 && kk.f < 1;
    pr.g.rotation.y = moving ? Math.atan2(-dz, dx) : Math.PI / 2;
    if (r > 2.45 && !moving) pr.g.rotation.y = 0;
    const sc = Math.min(smooth((r + 3.4) / 0.4), 1 - smooth((r - 3.7) / 0.4));
    pr.g.scale.setScalar(Math.max(0.001, 0.85 * sc));
    const w = moving ? Math.sin(lt * 22 + c.s) * 0.5 : 0;
    pr.legs[0].rotation.z = w; pr.legs[1].rotation.z = -w;
    pr.g.position.y = 0.12 + (moving ? Math.abs(Math.sin(lt * 22 + c.s)) * 0.03 : 0);
    const hasCup = r >= 2.4;
    pr.cup.visible = hasCup;
    pr.arms[0].rotation.z = hasCup ? 0.9 : (r >= 0.2 && r < 0.6 ? 0.9 + 0.2 * Math.sin(lt * 18) : -w * 0.5);
    pr.arms[1].rotation.z = w * 0.5;
  }
  for (const sp of shopG.sippers){
    const u = mod(lt / 5 + sp.ph, 1);
    sp.pr.arms[0].rotation.z = 1.9 * smooth(u / 0.2) * (1 - smooth((u - 0.45) / 0.2));
  }
  for (const ty of shopG.typers){
    ty.arms[0].rotation.z = 1.25 + 0.1 * Math.sin(lt * 31);
    ty.arms[1].rotation.z = 1.25 + 0.1 * Math.sin(lt * 29 + 1);
  }
}

/* ---------- people ---------- */
function person(shirt, o = {}){
  const g = new THREE.Group();
  const skin = o.skin ?? pick(C.skin), pants = o.pants ?? pick([C.navy, 0x3a4566, 0x5d6a86]), hair = pick(C.hair);
  const legs = [];
  for (const sz of [-0.075, 0.075]){
    const lg = new THREE.Group(); lg.position.set(0, 0.34, sz);
    box(lg, 0.12, 0.34, 0.11, pants, 0, -0.17, 0, { r: 0.04 });
    g.add(lg); legs.push(lg);
  }
  box(g, 0.22, 0.38, 0.32, shirt, 0, 0.53, 0, { r: 0.08 });
  if (o.apron) box(g, 0.04, 0.3, 0.26, C.orange, 0.12, 0.5, 0, { r: 0.015 });
  const arms = [];
  for (const sz of [-0.2, 0.2]){
    const ag = new THREE.Group(); ag.position.set(0, 0.68, sz);
    box(ag, 0.1, 0.3, 0.08, shirt, 0, -0.14, 0, { r: 0.035 });
    g.add(ag); arms.push(ag);
  }
  box(g, 0.2, 0.2, 0.2, skin, 0, 0.84, 0, { r: 0.07 });
  box(g, 0.22, 0.08, 0.22, hair, -0.01, 0.96, 0, { r: 0.035 });
  return { g, legs, arms };
}
const shirts = [C.royal, C.teal, C.green, C.white, C.navy, C.tealLight, C.greenLight, C.royalDeep];

// queue path (world coords on block sidewalk)
const QP = [[6.05, 6.15], [5.6, 5.3], [4.9, 5.3], [4.2, 5.3], [3.5, 5.3], [2.8, 5.3], [2.15, 5.25], [1.5, 4.75], [1.5, 4.75]];
const QN = 8, STEP = IN.step;
const queue = [];
for (let k = 0; k < 0; k++){
  const p = prop(QP[k][0], BY, QP[k][1]);
  const pr = person(shirts[k % shirts.length]);
  pr.g.scale.setScalar(0.85);
  p.inner.add(pr.g);
  // a few carry an orange cup
  queue.push({ p, pr, k });
}

// café tables with sipping customers on the side sidewalk
const sippers = [];
for (const [tx, tz, ph] of []){
  const p = prop(tx, BY, tz);
  const g = p.inner;
  boxB(g, 0.08, 1.4, 0.08, C.navy, 0, 0, 0, { r: 0.03 });
  const um = boxB(g, 1.5, 0.1, 1.5, C.orange, 0, 1.4, 0, { r: 0.05 });
  boxB(g, 0.7, 0.06, 0.7, C.white, 0, 0.5, 0, { r: 0.03 });
  boxB(g, 0.06, 0.5, 0.06, C.navy, 0, 0, 0, { r: 0.02 });
  boxB(g, 0.16, 0.16, 0.16, C.white, 0.12, 0.56, 0.12, { r: 0.04 });
  for (const sz of [-0.55, 0.55]){
    boxB(g, 0.36, 0.3, 0.36, C.teal, 0, 0, sz, { r: 0.06 });
    const pr = person(pick(shirts));
    pr.g.scale.setScalar(0.82);
    pr.g.position.set(0, 0.06, sz);
    pr.g.rotation.y = sz > 0 ? Math.PI / 2 : -Math.PI / 2;
    pr.legs.forEach(l => (l.rotation.z = Math.PI / 2.2));
    g.add(pr.g);
    const cupM = box(pr.arms[0], 0.12, 0.14, 0.12, C.white, 0, -0.3, 0, { r: 0.04 });
    box(cupM, 0.13, 0.05, 0.13, C.orange, 0, 0, 0, { r: 0.02 });
    sippers.push({ pr, ph: ph + (sz > 0 ? 0.25 : 0) });
  }
}

/* ---------- vehicles ---------- */
function wheel(parent, x, y, z, r, side){
  const w = new THREE.Group(); w.position.set(x, y, z); parent.add(w);
  box(w, r * 2, r * 2, 0.14, C.tire, 0, 0, 0, { r: r * 0.45 });
  box(w, r * 0.9, r * 0.9, 0.04, C.stone, 0, 0, side * 0.07, { r: 0.02 });
  return w;
}
function car(color){
  const g = new THREE.Group(), wheels = [];
  box(g, 1.5, 0.4, 0.82, color, 0, 0.38, 0, { r: 0.15 });
  box(g, 0.86, 0.34, 0.74, C.glass, -0.1, 0.72, 0, { r: 0.12, rough: 0.18, metal: 0.1 });
  box(g, 0.82, 0.07, 0.72, color, -0.1, 0.9, 0, { r: 0.03 });
  for (const s of [-0.26, 0.26]){
    box(g, 0.05, 0.09, 0.16, C.white, 0.75, 0.42, s, { r: 0.02, emissive: 0xfff3d6, ei: 0.5, cast: false });
    box(g, 0.05, 0.09, 0.16, C.navy, -0.75, 0.42, s, { r: 0.02, cast: false });
  }
  for (const wx of [-0.48, 0.48]) for (const wz of [-0.38, 0.38]) wheels.push(wheel(g, wx, 0.17, wz, 0.17, Math.sign(wz)));
  return { g, wheels, r: 0.17 };
}
function bus(color){
  const g = new THREE.Group(), wheels = [];
  box(g, 3.0, 0.95, 0.95, color, 0, 0.66, 0, { r: 0.18 });
  box(g, 2.7, 0.34, 0.98, C.glass, -0.05, 0.86, 0, { r: 0.08, rough: 0.18 });
  box(g, 0.06, 0.5, 0.8, C.glass, 1.49, 0.8, 0, { r: 0.03, rough: 0.18 });
  box(g, 2.9, 0.08, 0.9, C.white, 0, 1.16, 0, { r: 0.03 });
  box(g, 0.8, 0.18, 0.6, C.white, -0.4, 1.28, 0, { r: 0.06 });
  for (const wx of [-1.0, 1.0]) for (const wz of [-0.44, 0.44]) wheels.push(wheel(g, wx, 0.2, wz, 0.2, Math.sign(wz)));
  return { g, wheels, r: 0.2 };
}
function scooter(){
  const g = new THREE.Group(), wheels = [];
  box(g, 0.66, 0.16, 0.26, C.white, 0, 0.3, 0, { r: 0.06 });
  box(g, 0.24, 0.24, 0.26, C.teal, 0.26, 0.42, 0, { r: 0.07 });
  box(g, 0.07, 0.42, 0.07, C.navy, 0.34, 0.6, 0, { r: 0.025 });
  box(g, 0.06, 0.05, 0.42, C.navy, 0.34, 0.82, 0, { r: 0.02 });
  box(g, 0.3, 0.08, 0.24, C.navy, -0.1, 0.44, 0, { r: 0.03 });
  box(g, 0.38, 0.36, 0.38, C.orange, -0.34, 0.68, 0, { r: 0.07, emissive: C.orange, ei: 0.08 });
  // rider
  box(g, 0.22, 0.36, 0.3, C.royal, -0.04, 0.68, 0, { r: 0.08 });
  for (const sz of [-0.13, 0.13]){ const a = box(g, 0.34, 0.08, 0.08, C.royal, 0.14, 0.76, sz, { r: 0.03 }); a.rotation.z = -0.4; }
  box(g, 0.2, 0.18, 0.2, pick(C.skin), -0.02, 0.96, 0, { r: 0.07 });
  box(g, 0.26, 0.14, 0.26, C.teal, -0.03, 1.08, 0, { r: 0.1 });
  for (const wx of [-0.3, 0.32]) wheels.push(wheel(g, wx, 0.14, 0, 0.14, 1));
  return { g, wheels, r: 0.14 };
}

const innerLane = makePath(7.75, 1.4), outerLane = makePath(9.55, 1.8), bikeLane = makePath(6.88, 1.0);
const vehicles = [];
function addVehicle(v, path, rev, offset){
  const p = prop(0, RY, 0);
  p.inner.add(v.g);
  vehicles.push({ ...v, p, path, rev, offset, K: Math.max(1, Math.round(path.L / (TAU * v.r))) });
}
[C.royal, C.white, C.teal].forEach((c, i) => addVehicle(car(c), innerLane, false, i * innerLane.L / 3 + 3));
addVehicle(bus(C.green), outerLane, true, 0);
[C.royalDeep, C.tealLight].forEach((c, i) => addVehicle(car(c), outerLane, true, (i + 1) * outerLane.L / 3));

// scooters parked at the shop curb, leave on a delivery lap and come back
const k0 = 6.88 - 1.0;
const scooters = [
  { s0: 4.25 + k0, dep: 1.5, dur: 7.0 },
  { s0: 3.35 + k0, dep: 3.0, dur: 7.0 }
].map(sc => {
  const v = scooter();
  const p = prop(0, RY, 0);
  p.inner.add(v.g);
  return { ...sc, ...v, p, K: Math.round(bikeLane.L / (TAU * v.r)) };
});

/* ---------- street furniture ---------- */
const trees = [];
function tree(x, z, y = 0, size = 1){
  const p = prop(x, y, z);
  const g = p.inner; g.scale.setScalar(size);
  boxB(g, 0.5, 0.12, 0.5, C.stone, 0, 0, 0, { r: 0.05 });
  boxB(g, 0.16, 0.8, 0.16, C.trunk, 0, 0.1, 0, { r: 0.05 });
  const fol = new THREE.Group(); fol.position.y = 0.8; g.add(fol);
  const c1 = pick([C.green, C.greenDeep, C.teal]);
  box(fol, 0.95, 0.85, 0.95, c1, 0, 0.42, 0, { r: 0.3 });
  box(fol, 0.66, 0.6, 0.66, pick([C.greenLight, C.green]), 0.08, 1.0, -0.05, { r: 0.22 });
  fol.rotation.y = rnd() * TAU;
  trees.push({ fol, ph: rnd() * TAU });
}
function lamp(x, z, rotY, y = 0){
  const p = prop(x, y, z);
  const g = p.inner; g.rotation.y = rotY;
  boxB(g, 0.28, 0.1, 0.28, C.navy, 0, 0, 0, { r: 0.04 });
  boxB(g, 0.09, 2.3, 0.09, C.navy, 0, 0.05, 0, { r: 0.03 });
  box(g, 0.62, 0.07, 0.07, C.navy, 0.28, 2.32, 0, { r: 0.02 });
  box(g, 0.36, 0.12, 0.22, C.navy, 0.56, 2.26, 0, { r: 0.05 });
  box(g, 0.28, 0.04, 0.16, C.white, 0.56, 2.19, 0, { r: 0.015, emissive: 0xfff1d0, ei: 0.9, cast: false });
}
function bench(x, z, rotY){
  const p = prop(x, 0, z);
  const g = p.inner; g.rotation.y = rotY;
  for (const lx of [-0.4, 0.4]) boxB(g, 0.08, 0.3, 0.34, C.navy, lx, 0, 0, { r: 0.02 });
  boxB(g, 1.1, 0.08, 0.38, C.teal, 0, 0.3, 0, { r: 0.03 });
  boxB(g, 1.1, 0.3, 0.06, C.teal, 0, 0.38, -0.17, { r: 0.03 });
}
function hydrant(x, z, y){
  const p = prop(x, y, z);
  boxB(p.inner, 0.2, 0.36, 0.2, C.royal, 0, 0, 0, { r: 0.07 });
  box(p.inner, 0.32, 0.08, 0.1, C.royal, 0, 0.22, 0, { r: 0.03 });
  boxB(p.inner, 0.24, 0.07, 0.24, C.royalDeep, 0, 0.36, 0, { r: 0.03 });
}
function bin(x, z, y){
  const p = prop(x, y, z);
  boxB(p.inner, 0.3, 0.46, 0.3, C.greenDeep, 0, 0, 0, { r: 0.07 });
  boxB(p.inner, 0.34, 0.06, 0.34, C.navy, 0, 0.46, 0, { r: 0.02 });
}

// outer ring (slab sidewalk between road and edge)
const O = 11.8;
for (const u of [-9.5, -4.5, 1.5, 6.5]){ tree(u, -O); tree(-O, u); }
for (const u of [-8, -2.5]){ tree(u, O, 0, 0.9); tree(O, u, 0, 0.9); }
tree(O, O, 0, 1.1); tree(-O, -O, 0, 1.2); tree(O, -O, 0, 1.05); tree(-O, O, 0, 1.05);
for (const u of [-6.5, 4.0]){ lamp(u, 11.0, Math.PI / 2); lamp(11.0, u, 0); lamp(u, -11.0, -Math.PI / 2); lamp(-11.0, u, Math.PI); }
bench(9.0, 12.2, Math.PI); bench(12.2, 8.5, -Math.PI / 2); bench(-1.5, -12.2, 0);
// inner block sidewalk
lamp(6.0, -1.0, Math.PI, BY); lamp(-1.0, 6.0, -Math.PI / 2, BY); lamp(-6.0, 0.4, 0, BY);
tree(-0.1, 1.7, BY, 0.85); tree(-0.1, 4.4, BY, 0.8); tree(0.3, -5.8, BY, 0.75);
hydrant(6.0, -2.4, BY); bin(0.6, 5.9, BY); bin(6.0, 0.5, BY);

// pedestrians on the outer sidewalk
const walkers = [];
function addWalker(axis, fixed, from, to, shirt, dog){
  const p = prop(0, 0, 0);
  const pr = person(shirt); pr.g.scale.setScalar(0.85); p.inner.add(pr.g);
  let d = null;
  if (dog){
    d = new THREE.Group(); p.inner.add(d);
    box(d, 0.42, 0.2, 0.18, C.white, 0, 0.24, 0, { r: 0.07 });
    box(d, 0.18, 0.18, 0.16, C.white, 0.26, 0.36, 0, { r: 0.06 });
    box(d, 0.06, 0.08, 0.16, C.navy, 0.3, 0.46, 0, { r: 0.02 });
    for (const lx of [-0.14, 0.14]) for (const lz of [-0.06, 0.06]) boxB(d, 0.06, 0.14, 0.06, C.navy, lx, 0, lz, { r: 0.02 });
    box(d, 0.14, 0.04, 0.04, C.white, -0.26, 0.34, 0, { r: 0.015 });
  }
  walkers.push({ p, pr, axis, fixed, from, to, d });
}
addWalker('x', 11.6, -12.4, 12.4, C.royal, true);
addWalker('x', 12.3, 12.4, -12.4, C.green, false);
addWalker('z', 11.7, 12.4, -12.4, C.teal, false);
addWalker('z', 12.35, -12.4, 12.4, C.white, false);

/* ---------- post-processing ---------- */
const rt = new THREE.WebGLRenderTarget(W, H, { type: THREE.HalfFloatType, samples: 4 });
const composer = new EffectComposer(renderer, rt);
composer.setPixelRatio(1);
composer.setSize(W, H);
composer.addPass(new RenderPass(scene, camera));
try {
  const gtao = new GTAOPass(scene, camera, W, H);
  gtao.output = GTAOPass.OUTPUT.Default;
  gtao.blendIntensity = 1.0;
  gtao.updateGtaoMaterial({ radius: 0.3, distanceExponent: 1.4, thickness: 1.2, scale: 1.15, samples: 12, distanceFallOff: 1, screenSpaceRadius: false });
  gtao.updatePdMaterial({ lumaPhi: 10, depthPhi: 2, normalPhi: 3, radius: 6, radiusExponent: 1, rings: 2, samples: 16 });
  composer.addPass(gtao);
} catch (e) { console.warn('GTAO unavailable', e); }
composer.addPass(new OutputPass());

/* ---------- overlay stats ---------- */
const elO = document.getElementById('sOrders'), elR = document.getElementById('sRev'), elD = document.getElementById('sDel'), elDR = document.getElementById('dRev');
const fmtInt = n => n.toLocaleString('en-US');
const price = i => { const x = Math.sin(i * 12.9898) * 43758.5453; return 3.5 + (x - Math.floor(x)) * 6.5; };
let lastOrders = -1, lastDel = -1, revTarget = 6842.5, revShown = 6842.5, revIdx = 0;
function bump(el){ el.classList.remove('bump'); void el.offsetWidth; el.classList.add('bump'); }
function updateStats(t, lt){
  const n = t < IN.svc0 + 0.5 ? 0 : Math.floor((t - IN.svc0 - 0.5) / STEP) + 1;
  while (revIdx < n){ revTarget += price(revIdx++); }
  const orders = 1284 + n;
  if (orders !== lastOrders){ elO.textContent = fmtInt(orders); if (lastOrders >= 0) bump(elO); lastOrders = orders; }
  const del = 212 + 2 * Math.floor(t / LOOP) + (lt >= 1.5) + (lt >= 3.0);
  if (del !== lastDel){ elD.textContent = fmtInt(del); if (lastDel >= 0) bump(elD); lastDel = del; }
  const prev = Math.floor(revShown);
  revShown += (revTarget - revShown) * 0.12;
  if (Math.floor(revShown) !== prev){
    elR.textContent = '$' + fmtInt(Math.floor(revShown));
    elDR.textContent = 'avg ticket $' + (revShown / orders).toFixed(2);
  }
  if (revTarget - revShown > 2 && !elR.classList.contains('bump')) bump(elR);
}

/* ---------- animation ---------- */
let start = null;
const card = document.querySelector('.card');
function restart(){
  start = null; buildDone = false;
  lastOrders = -1; lastDel = -1; revTarget = 6842.5; revShown = 6842.5; revIdx = 0;
  elR.textContent = '$6,842';
  card.style.animation = 'none'; void card.offsetWidth; card.style.animation = '';
}
addEventListener('keydown', e => { if (e.code === 'Space' || e.key === 'r' || e.key === 'R') { e.preventDefault(); restart(); } });
addEventListener('pointerdown', restart);
function frame(now){
  if (start === null) start = now;
  const t = (window.__freezeT ?? (now - start) / 1000), lt = t % LOOP, ph = lt / LOOP;
  applyBuild(t);

  // camera: eased sway-orbit with gentle push in, period = LOOP
  placeCamera(t);
  animateOpen(t);

  // cars: one lap per loop
  for (const v of vehicles){
    const pt = v.path.at(v.offset + ph * v.path.L, v.rev);
    v.p.root.position.set(pt.x, RY, pt.z);
    v.p.root.rotation.y = pt.yaw;
    const spin = -ph * TAU * v.K;
    v.wheels.forEach(w => (w.rotation.z = spin));
  }

  // scooters
  for (const sc of scooters){
    const u = smooth((lt - sc.dep) / sc.dur);
    const pt = bikeLane.at(sc.s0 + u * bikeLane.L, false);
    const lean = Math.sin(u * Math.PI);
    sc.p.root.position.set(pt.x, RY, pt.z);
    sc.p.root.rotation.y = pt.yaw;
    sc.g.position.y = 0.03 * lean * Math.abs(Math.sin(lt * 18));
    sc.wheels.forEach(w => (w.rotation.z = -u * TAU * sc.K));
  }

  // queue: every STEP seconds everyone shuffles forward one slot
  const step = Math.floor(lt / STEP), fr = (lt % STEP) / STEP;
  const move = smooth(fr / 0.5);
  for (const q of queue){
    const u = (q.k + step + move) % QN;
    const i = Math.floor(u), f = u - i;
    const a = QP[i], b = QP[i + 1];
    const x = a[0] + (b[0] - a[0]) * f, z = a[1] + (b[1] - a[1]) * f;
    q.p.root.position.set(x, BY, z);
    const dx = b[0] - a[0], dz = b[1] - a[1];
    if (Math.hypot(dx, dz) > 0.01) q.p.root.rotation.y = Math.atan2(-dz, dx);
    let s = 1;
    if (u < 1) s = smooth(u * 1.4);
    else if (u >= 6) s = 1 - smooth((u - 6) / 0.9);
    q.pr.g.scale.setScalar(Math.max(0.001, 0.85 * s));
    q.pr.g.visible = s > 0.01;
    const moving = fr < 0.5 ? Math.sin(fr / 0.5 * Math.PI) : 0;
    const sw = Math.sin(lt * 14 + q.k) * 0.55 * moving;
    q.pr.legs[0].rotation.z = sw; q.pr.legs[1].rotation.z = -sw;
    q.pr.g.position.y = Math.abs(Math.sin(lt * 14 + q.k)) * 0.04 * moving;
  }

  // walkers along the outer sidewalk
  for (const w of walkers){
    const v = w.from + (w.to - w.from) * ph;
    const dir = Math.sign(w.to - w.from);
    if (w.axis === 'x'){ w.p.root.position.set(v, 0, w.fixed); w.p.root.rotation.y = dir > 0 ? 0 : Math.PI; }
    else { w.p.root.position.set(w.fixed, 0, v); w.p.root.rotation.y = dir > 0 ? -Math.PI / 2 : Math.PI / 2; }
    const edge = Math.min(Math.abs(v - w.from), Math.abs(v - w.to));
    const s = smooth(edge / 0.8);
    w.p.root.scale.setScalar(Math.max(0.001, s));
    const sw = Math.sin(ph * TAU * 14) * 0.55;
    w.pr.legs[0].rotation.z = sw; w.pr.legs[1].rotation.z = -sw;
    w.pr.arms[0].rotation.z = -sw * 0.6; w.pr.arms[1].rotation.z = sw * 0.6;
    w.pr.g.position.y = Math.abs(Math.sin(ph * TAU * 14)) * 0.035;
    if (w.d){ w.d.position.set(0.75, Math.abs(Math.sin(ph * TAU * 28)) * 0.05, 0.35); }
  }

  // ambient motion
  for (const tr of trees){ tr.fol.rotation.z = 0.035 * Math.sin(ph * TAU * 2 + tr.ph); tr.fol.rotation.x = 0.025 * Math.cos(ph * TAU * 2 + tr.ph); }
  fans.forEach((f, i) => (f.rotation.y = ph * TAU * (6 + i)));
  blinkers.forEach(b => (b.material.emissiveIntensity = (lt % 1) < 0.35 ? 2.2 : 0));
  for (const st of steam){
    const u = (ph * 4 + st.phase) % 1;
    st.m.position.set(Math.sin(u * TAU + st.phase * 9) * 0.14, 1.25 + u * 1.7, Math.cos(u * 5 + st.phase * 4) * 0.12);
    st.m.scale.setScalar(0.35 + u * 1.1);
    st.m.material.opacity = 0.85 * Math.sin(u * Math.PI);
    st.m.rotation.y = u * 2;
  }
  for (const sp of sippers){
    const u = (ph * 2 + sp.ph) % 1;
    const lift = smooth(u / 0.2) * (1 - smooth((u - 0.45) / 0.2));
    sp.pr.arms[0].rotation.z = 1.9 * lift;
    sp.pr.g.position.y = 0.06;
  }
  animateShop(lt);

  updateStats(t, lt);
  composer.render();
  requestAnimationFrame(frame);
}
window.__sceneOK = true;
requestAnimationFrame(frame);
</script>
</body>
</html>
canh-3d-video-doc/04-nha-may-ai-neuroforge.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
</head>
<body>
<title>NeuroForge AI Factory</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,800&family=Manrope:wght@500;600;700;800&display=swap">
<style>
/* Layout: fixed 1088x1920 frame scaled to fit the window; frosted card floats over the top third, diorama sits low. */
:root{
  --bg:#e9ecf1;
  --frame:#f6f7f9;
  --ink:#141b38;
  --muted:#5a6383;
  --accent:#ff7a1c;
  --royal:#2f55e6;
  --teal:#17a99c;
  --green:#3db86a;
  --f-display:'Bricolage Grotesque','Manrope',system-ui,sans-serif;
  --f-body:'Manrope',system-ui,-apple-system,'Segoe UI',sans-serif;
  color-scheme:light;
}
html,body{height:100%;margin:0;overflow:hidden;background:var(--bg);color:var(--ink)}
#stage{
  position:absolute;left:50%;top:50%;
  width:1088px;height:1920px;
  transform:translate(-50%,-50%) scale(var(--s,0.4));
  transform-origin:center center;
  overflow:hidden;background:var(--frame);
}
#c{position:absolute;inset:0;display:block;width:1088px;height:1920px}
.vignette{position:absolute;inset:0;pointer-events:none;
  background:radial-gradient(120% 80% at 50% 60%, rgba(255,255,255,0) 55%, rgba(20,27,56,.07) 100%)}
.card{
  position:absolute;left:84px;right:84px;top:132px;
  padding:42px 48px 44px;border-radius:44px;
  background:linear-gradient(160deg, rgba(255,255,255,.62), rgba(255,255,255,.34));
  -webkit-backdrop-filter:blur(26px) saturate(1.5);backdrop-filter:blur(26px) saturate(1.5);
  border:1.5px solid rgba(255,255,255,.85);
  box-shadow:0 30px 80px -30px rgba(20,27,56,.35), inset 0 1px 0 rgba(255,255,255,.9);
  font-family:var(--f-body);
  opacity:0;transform:translateY(-24px) scale(.98);
  animation:cardIn .7s cubic-bezier(.2,.9,.25,1.15) .55s forwards;
}
@keyframes cardIn{to{opacity:1;transform:none}}
.head{display:flex;align-items:center;justify-content:space-between;gap:24px}
.brand{display:flex;align-items:center;gap:22px;min-width:0}
.mark{flex:none;width:68px;height:68px;border-radius:22px;background:var(--accent);display:grid;place-items:center;
  box-shadow:0 10px 24px -8px rgba(255,122,28,.7)}
.mark svg{width:42px;height:42px}
h1{margin:0;font-family:var(--f-display);font-weight:800;font-size:54px;line-height:1;letter-spacing:-.02em;text-wrap:balance}
h1 span{color:var(--muted);font-weight:600}
.sub{margin:10px 0 0;font-size:22px;font-weight:600;color:var(--muted);letter-spacing:.01em;font-variant-numeric:tabular-nums}
.live{flex:none;display:flex;align-items:center;gap:12px;padding:12px 20px;border-radius:999px;
  background:rgba(20,27,56,.9);color:#fff;font-weight:800;font-size:20px;letter-spacing:.16em}
.live i{width:14px;height:14px;border-radius:50%;background:var(--accent);animation:pulse 1s ease-out infinite}
@keyframes pulse{0%{box-shadow:0 0 0 0 rgba(255,122,28,.75)}100%{box-shadow:0 0 0 16px rgba(255,122,28,0)}}
.stats{display:grid;grid-template-columns:1.2fr 1.1fr 1fr;margin-top:36px;border-top:1.5px solid rgba(20,27,56,.09)}
.stat{padding:30px 0 0 28px;display:flex;flex-direction:column;gap:10px;min-width:0;border-left:1.5px solid rgba(20,27,56,.09)}
.stat:first-child{padding-left:0;border-left:0}
.label{font-size:18px;font-weight:800;text-transform:uppercase;letter-spacing:.13em;color:var(--muted);display:flex;align-items:center;gap:10px;white-space:nowrap}
.label b{width:12px;height:12px;border-radius:4px;display:inline-block;flex:none}
.val{font-weight:800;font-size:62px;line-height:1;letter-spacing:-.03em;font-variant-numeric:tabular-nums;color:var(--ink);display:inline-block;transform-origin:left bottom;white-space:nowrap}
.val.bump{animation:bump .55s ease-out}
@keyframes bump{0%{color:var(--accent);transform:translateY(-6px) scale(1.04)}100%{color:var(--ink);transform:none}}
.delta{font-size:20px;font-weight:700;color:var(--teal);font-variant-numeric:tabular-nums;white-space:nowrap}
@media (prefers-reduced-motion: reduce){.card{animation-duration:.01s}.live i{animation:none}}
</style>

<div id="stage">
  <canvas id="c" width="1088" height="1920"></canvas>
  <div class="vignette"></div>
  <section class="card" aria-label="NeuroForge live output">
    <div class="head">
      <div class="brand">
        <div class="mark" aria-hidden="true">
          <svg viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2.2" stroke-linecap="round"><rect x="6" y="6" width="12" height="12" rx="2.5" fill="#fff" stroke="none"/><path d="M9 2.5v2.5M12 2.5v2.5M15 2.5v2.5M9 19v2.5M12 19v2.5M15 19v2.5M2.5 9h2.5M2.5 12h2.5M2.5 15h2.5M19 9h2.5M19 12h2.5M19 15h2.5"/><rect x="9.5" y="9.5" width="5" height="5" rx="1" fill="#ff7a1c" stroke="none"/></svg>
        </div>
        <div>
          <h1>NeuroForge <span>· Live Output</span></h1>
          <p class="sub">Campus 01 · 312 MW · PUE 1.12</p>
        </div>
      </div>
      <div class="live"><i></i>LIVE</div>
    </div>
    <div class="stats">
      <div class="stat">
        <span class="label"><b style="background:var(--royal)"></b>Tokens</span>
        <span class="val" id="sTok">48.214B</span>
        <span class="delta">+4.1M tok/s</span>
      </div>
      <div class="stat">
        <span class="label"><b style="background:var(--teal)"></b>GPUs online</span>
        <span class="val" id="sGpu">24,576</span>
        <span class="delta">+8 per node</span>
      </div>
      <div class="stat">
        <span class="label"><b style="background:var(--accent)"></b>Shipped</span>
        <span class="val" id="sMod">1,207</span>
        <span class="delta" id="dMod">1 drone out</span>
      </div>
    </div>
  </section>
</div>

<div id="err" hidden style="position:fixed;left:16px;right:16px;bottom:16px;padding:14px 16px;border-radius:12px;background:#141b38;color:#fff;font:600 14px/1.4 Manrope,system-ui,sans-serif;z-index:9"></div>
<script>
(function(){
  var el=document.getElementById('err');
  function show(m){ el.hidden=false; el.textContent='Không chạy được cảnh 3D: '+m; }
  window.addEventListener('error',function(e){ show(e.message||'lỗi tải script'); },true);
  window.addEventListener('unhandledrejection',function(e){ show(String(e.reason&&e.reason.message||e.reason)); });
  setTimeout(function(){ if(!window.__sceneOK) show('thư viện Three.js chưa tải xong sau 15 giây (mạng hoặc CDN bị chặn).'); },15000);
})();
</script>
<script type="importmap">
{ "imports": {
  "three": "https://cdn.jsdelivr.net/npm/three@0.160.0/+esm"
} }
</script>

<script type="module">
import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.160.0/+esm';
import { RoundedBoxGeometry } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/geometries/RoundedBoxGeometry.js/+esm';
import { EffectComposer } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/EffectComposer.js/+esm';
import { RenderPass } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/RenderPass.js/+esm';
import { GTAOPass } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/GTAOPass.js/+esm';
import { OutputPass } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/OutputPass.js/+esm';

const W = 1088, H = 1920, LOOP = 10, TAU = Math.PI * 2;
const STEP = 1.25;            // one chip placed every STEP seconds (8 per loop)
const BELT_V = 0.85;          // conveyor speed, units/s

const stage = document.getElementById('stage');
function fit(){ stage.style.setProperty('--s', Math.min(innerWidth / W, innerHeight / H)); }
addEventListener('resize', fit); fit();

const C = {
  ground:0xf7f6f2, base:0x2a48d4, road:0xd2d7e0, walk:0xe6e9ee, line:0xffffff,
  royal:0x2f55e6, royalDeep:0x2340b8, teal:0x17a99c, tealDeep:0x0f877d, tealLight:0x93e0d6,
  green:0x3db86a, greenDeep:0x22864a, greenLight:0x92dba6,
  orange:0xff7a1c, white:0xffffff, navy:0x1d2547, panel:0x2a3566, tire:0x2b3040, glass:0xcdeef4,
  trunk:0x8d847b, stone:0xc9ced8,
  skin:[0xf2cba8,0xdba57e,0xae7652,0x7d5136]
};

function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296}}
const rnd = mulberry32(7);
const pick = arr => arr[Math.floor(rnd() * arr.length)];
const clamp01 = x => Math.min(1, Math.max(0, x));
const smooth = x => { x = clamp01(x); return x * x * (3 - 2 * x); };
const easeOutCubic = x => 1 - Math.pow(1 - clamp01(x), 3);
const easeOutBack = x => { const c1 = 2.1, c3 = c1 + 1; return 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2); };
const mod = (a, n) => ((a % n) + n) % n;
const lerp = (a, b, t) => a + (b - a) * t;

/* ---------- renderer ---------- */
const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('c'), antialias: true, powerPreference: 'high-performance' });
renderer.setPixelRatio(1);
renderer.setSize(W, H, false);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;

const scene = new THREE.Scene();
scene.background = new THREE.Color(0xf7f8fa);
const camera = new THREE.PerspectiveCamera(32, W / H, 60, 260);
camera.setViewOffset(W, H, 0, -250, W, H);

scene.add(new THREE.HemisphereLight(0xeef3ff, 0xd8d3c8, 1.35));
const sun = new THREE.DirectionalLight(0xfff4e6, 2.7);
sun.position.set(-12, 26, 14);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
Object.assign(sun.shadow.camera, { left:-20, right:20, top:20, bottom:-20, near:1, far:80 });
sun.shadow.bias = -0.0004;
sun.shadow.normalBias = 0.025;
sun.shadow.radius = 5;
scene.add(sun);

/* ---------- helpers ---------- */
const geoCache = new Map(), matCache = new Map();
function geo(w, h, d, r){
  r = r ?? Math.min(0.14, Math.min(w, h, d) * 0.22);
  r = Math.min(r, Math.min(w, h, d) / 2 - 0.001);
  const k = [w, h, d, r].map(v => v.toFixed(3)).join('|');
  if (!geoCache.has(k)) geoCache.set(k, new RoundedBoxGeometry(w, h, d, 2, r));
  return geoCache.get(k);
}
function mat(color, o = {}){
  const k = [color, o.rough, o.metal, o.emissive, o.ei, o.opacity].join('|');
  if (!matCache.has(k)) matCache.set(k, new THREE.MeshStandardMaterial({
    color, roughness: o.rough ?? 0.62, metalness: o.metal ?? 0,
    emissive: o.emissive ?? 0x000000, emissiveIntensity: o.ei ?? 1,
    transparent: o.opacity !== undefined, opacity: o.opacity ?? 1,
    depthWrite: o.opacity === undefined
  }));
  return matCache.get(k);
}
function box(parent, w, h, d, color, x = 0, y = 0, z = 0, o = {}){
  const m = new THREE.Mesh(geo(w, h, d, o.r), o.material || mat(color, o));
  m.position.set(x, y, z);
  m.castShadow = o.cast !== false;
  m.receiveShadow = true;
  parent.add(m);
  return m;
}
const boxB = (p, w, h, d, c, x = 0, y = 0, z = 0, o) => box(p, w, h, d, c, x, y + h / 2, z, o);
const glowMat = (color, emissive, ei = 0) => new THREE.MeshStandardMaterial({ color, emissive, emissiveIntensity: ei, roughness: 0.4 });

/* ---------- build-in ---------- */
const builds = [];
function prop(x, y, z, delay){
  const root = new THREE.Group(); root.position.set(x, y, z);
  const inner = new THREE.Group(); root.add(inner);
  scene.add(root);
  builds.push({ inner, delay: delay ?? (0.16 + (Math.hypot(x, z) / 18) * 0.5 + rnd() * 0.12) });
  return { root, inner };
}
let buildDone = false;
function applyBuild(t){
  if (buildDone) return;
  let all = true;
  for (const b of builds){
    const x = clamp01((t - b.delay) / 0.42);
    if (x < 1) all = false;
    b.inner.visible = x > 0;
    b.inner.scale.setScalar(Math.max(0.001, easeOutBack(x)));
    b.inner.position.y = -1.6 * (1 - easeOutCubic(x));
  }
  if (all) buildDone = true;
}

/* ---------- ring-road lanes ---------- */
function makePath(h, rc){
  const a = 2 * (h - rc), arc = Math.PI * rc / 2, L = 4 * a + 4 * arc, k = h - rc;
  const starts = [[-k, h], [h, k], [k, -h], [-h, -k]];
  const dirs = [[1, 0], [0, -1], [-1, 0], [0, 1]];
  const centers = [[k, k], [k, -k], [-k, -k], [-k, k]];
  const th0 = [Math.PI / 2, 0, -Math.PI / 2, -Math.PI];
  return { L, at(s, rev){
    if (rev) s = L - s;
    s = mod(s, L);
    const seg = a + arc, i = Math.min(3, Math.floor(s / seg)), r = s - i * seg;
    let x, z, dx, dz;
    if (r < a){ x = starts[i][0] + dirs[i][0] * r; z = starts[i][1] + dirs[i][1] * r; dx = dirs[i][0]; dz = dirs[i][1]; }
    else { const th = th0[i] - (r - a) / rc; x = centers[i][0] + rc * Math.cos(th); z = centers[i][1] + rc * Math.sin(th); dx = Math.sin(th); dz = -Math.cos(th); }
    if (rev){ dx = -dx; dz = -dz; }
    return { x, z, yaw: Math.atan2(-dz, dx) };
  } };
}

/* ---------- window grids ---------- */
const _m = new THREE.Matrix4(), _q = new THREE.Quaternion(), _s = new THREE.Vector3(1, 1, 1), _v = new THREE.Vector3(), _p = new THREE.Vector3();
function windows(parent, { w, d, y0, floors, fh, cols, colsSide, ww = 0.5, wh = 0.62, color = C.glass, front = true, side = true }){
  const list = [];
  for (let f = 0; f < floors; f++){
    const y = y0 + f * fh;
    if (front) for (let c = 0; c < cols; c++) list.push([(c - (cols - 1) / 2) * (w / cols), y, d / 2, 0]);
    if (side) for (let c = 0; c < colsSide; c++) list.push([w / 2, y, (c - (colsSide - 1) / 2) * (d / colsSide), Math.PI / 2]);
  }
  const im = new THREE.InstancedMesh(geo(ww, wh, 0.1, 0.035), mat(color, { rough: 0.18, metal: 0.15 }), list.length);
  list.forEach(([x, y, z, ry], i) => { _q.setFromAxisAngle(_v.set(0, 1, 0), ry); _m.compose(_p.set(x, y, z), _q, _s); im.setMatrixAt(i, _m); });
  im.castShadow = true; im.receiveShadow = true;
  parent.add(im);
  return im;
}

/* ---------- people (engineers) ---------- */
function engineer(vest){
  const g = new THREE.Group();
  const skin = pick(C.skin), pants = pick([C.navy, 0x3a4566]);
  const legs = [];
  for (const sz of [-0.075, 0.075]){
    const lg = new THREE.Group(); lg.position.set(0, 0.34, sz);
    box(lg, 0.12, 0.34, 0.11, pants, 0, -0.17, 0, { r: 0.04 });
    g.add(lg); legs.push(lg);
  }
  box(g, 0.22, 0.38, 0.32, C.white, 0, 0.53, 0, { r: 0.08 });
  box(g, 0.24, 0.3, 0.34, vest, 0, 0.55, 0, { r: 0.08 });
  const arms = [];
  for (const sz of [-0.2, 0.2]){
    const ag = new THREE.Group(); ag.position.set(0, 0.68, sz);
    box(ag, 0.1, 0.3, 0.08, C.white, 0, -0.14, 0, { r: 0.035 });
    g.add(ag); arms.push(ag);
  }
  const head = new THREE.Group(); head.position.y = 0.84; g.add(head);
  box(head, 0.2, 0.2, 0.2, skin, 0, 0, 0, { r: 0.07 });
  box(head, 0.25, 0.1, 0.25, C.orange, 0, 0.12, 0, { r: 0.05 });
  box(head, 0.32, 0.03, 0.27, C.orange, 0.03, 0.08, 0, { r: 0.012 });
  return { g, legs, arms, head };
}

/* ======================================================================
   WORLD
   ====================================================================== */
const ROAD_IN = 7.2, ROAD_OUT = 10.8, BY = 0.22, RY = 0.06, FL = 0.08; // FL = building floor thickness

{ // slab
  const p = prop(0, 0, 0, 0);
  box(p.inner, 26, 1.0, 26, C.ground, 0, -0.5, 0, { r: 0.45 });
  box(p.inner, 25.2, 0.42, 25.2, C.base, 0, -1.12, 0, { r: 0.2, cast: false });
}
{ // ring road
  const p = prop(0, 0, 0, 0.06);
  box(p.inner, ROAD_OUT * 2, RY, ROAD_OUT * 2, C.road, 0, RY / 2, 0, { r: 0.03, cast: false });
  const h = 9.0, rc = 1.5;
  for (let side = 0; side < 4; side++){
    for (let u = -h + rc + 0.7; u < h - rc - 0.5; u += 1.3){
      const m = box(p.inner, 0.62, 0.02, 0.1, C.line, 0, RY + 0.01, 0, { r: 0.009, cast: false });
      if (side === 0) m.position.set(u, m.position.y, h);
      if (side === 1) { m.position.set(h, m.position.y, u); m.rotation.y = Math.PI / 2; }
      if (side === 2) m.position.set(u, m.position.y, -h);
      if (side === 3) { m.position.set(-h, m.position.y, u); m.rotation.y = Math.PI / 2; }
    }
  }
  for (let z = ROAD_IN + 0.35; z < ROAD_OUT - 0.2; z += 0.62) box(p.inner, 1.3, 0.02, 0.32, C.line, -0.4, RY + 0.012, z, { r: 0.009, cast: false });
  for (let x = ROAD_IN + 0.35; x < ROAD_OUT - 0.2; x += 0.62) box(p.inner, 0.32, 0.02, 1.3, C.line, x, RY + 0.012, -0.3, { r: 0.009, cast: false });
}
{ // campus plaza + walkways
  const p = prop(0, 0, 0, 0.1);
  box(p.inner, ROAD_IN * 2, BY, ROAD_IN * 2, C.walk, 0, BY / 2, 0, { r: 0.08 });
  box(p.inner, 0.9, 0.012, 13.8, C.tealLight, -0.4, BY + 0.006, 0, { r: 0.005, cast: false });
  box(p.inner, 7.4, 0.012, 0.9, C.tealLight, 3.1, BY + 0.006, -0.3, { r: 0.005, cast: false });
}

/* ---------- DATA HALL (back corner) ---------- */
const fans = [], blinkers = [], steam = [];
const racks = [];
const INGEST = { x: -4.0, z: -1.9 };
{
  const p = prop(-4.0, BY, -4.0, 0.2);
  const g = p.inner;
  boxB(g, 5.4, FL, 5.4, C.white);
  boxB(g, 0.3, 3.6, 5.4, C.royal, -2.55, 0, 0, { r: 0.1 });
  boxB(g, 5.4, 3.6, 0.3, C.royal, 0, 0, -2.55, { r: 0.1 });
  boxB(g, 0.34, 3.6, 0.34, C.royalDeep, 2.5, 0, 2.5, { r: 0.1 });
  boxB(g, 5.7, 0.34, 5.7, C.royal, 0, 3.6, 0, { r: 0.12 });
  boxB(g, 5.78, 0.1, 5.78, C.teal, 0, 3.5, 0, { r: 0.04 });
  // racks
  const rowsX = [1.7, 0.1, -1.5], colsZ = [1.25, 0.45, -0.35, -1.15, -1.95];
  for (const rx of rowsX){
    boxB(g, 0.34, 0.07, 4.3, C.stone, rx, 2.25, -0.35, { r: 0.03 });           // cable tray
    for (const rz of colsZ){
      boxB(g, 0.7, 1.7, 0.72, C.navy, rx, FL, rz, { r: 0.06 });
      boxB(g, 0.04, 1.5, 0.6, C.panel, rx + 0.36, FL + 0.1, rz, { r: 0.015 });
      const led = glowMat(0x9ff5ea, 0x2ee6d0, 0.3);
      for (const ly of [0.45, 0.85, 1.25]) box(g, 0.03, 0.06, 0.5, 0, rx + 0.39, FL + ly, rz, { r: 0.012, material: led, cast: false });
      const dot = glowMat(0xffffff, C.orange, 0);
      box(g, 0.03, 0.08, 0.08, 0, rx + 0.39, FL + 1.55, rz + 0.2, { r: 0.012, material: dot, cast: false });
      const wx = -4.0 + rx, wz = -4.0 + rz;
      racks.push({ led, dot, delay: Math.hypot(wx - INGEST.x, wz - INGEST.z) * 0.09, blink: 1 + Math.floor(rnd() * 4), ph: rnd() * TAU });
    }
  }
  // ingest unit where the conveyor ends
  boxB(g, 0.95, 0.95, 0.6, C.white, 0, FL, 2.1, { r: 0.1 });
  boxB(g, 0.7, 0.08, 0.06, C.teal, 0, FL + 0.75, 2.42, { r: 0.02 });
  // rooftop chillers
  const roof = 3.94;
  for (const [cx, cz] of [[-1.3, -1.2], [0.2, -1.2], [-1.3, 0.4]]){
    boxB(g, 1.2, 0.45, 1.2, C.stone, cx, roof, cz, { r: 0.12 });
    const f = new THREE.Group(); f.position.set(cx, roof + 0.5, cz); g.add(f);
    box(f, 0.95, 0.04, 0.14, C.navy, 0, 0, 0, { r: 0.02 });
    box(f, 0.14, 0.04, 0.95, C.navy, 0, 0, 0, { r: 0.02 });
    fans.push({ g: f, k: 9 });
  }
  boxB(g, 0.08, 1.4, 0.08, C.navy, 1.6, roof, 1.5, { r: 0.03 });
  const bl = boxB(g, 0.2, 0.2, 0.2, 0, 1.6, roof + 1.42, 1.5, { r: 0.08, material: glowMat(0xffffff, 0x7ff3e4, 0) });
  blinkers.push(bl);
}
/* ---------- chips ---------- */
const chipGlow = new THREE.MeshStandardMaterial({ color: 0xffb27a, emissive: C.orange, emissiveIntensity: 0.9, roughness: 0.4 });
function chipMesh(parent, x = 0, y = 0, z = 0){
  const g = new THREE.Group(); g.position.set(x, y, z); parent.add(g);
  boxB(g, 0.34, 0.05, 0.34, C.navy, 0, 0, 0, { r: 0.015 });
  boxB(g, 0.2, 0.03, 0.2, 0, 0, 0.045, 0, { r: 0.01, material: chipGlow, cast: false });
  for (const s of [-1, 1]){
    boxB(g, 0.3, 0.02, 0.03, C.stone, 0, 0.01, s * 0.18, { r: 0.008, cast: false });
    boxB(g, 0.03, 0.02, 0.3, C.stone, s * 0.18, 0.01, 0, { r: 0.008, cast: false });
  }
  return g;
}
/* ---------- CONVEYOR (factory -> data hall) ---------- */
const BELT_X = -4.0, BELT_Z0 = 5.6, BELT_Z1 = -2.0, SPAWN_Z = 5.0, END_Z = -1.95;
const BELT_TOP = BY + FL + 0.58;
const CHIP_T = (SPAWN_Z - END_Z) / BELT_V;
let slats;
{
  const len = BELT_Z0 - BELT_Z1, cz = (BELT_Z0 + BELT_Z1) / 2;
  const p = prop(BELT_X, BY + FL, cz, 0.3);
  const g = p.inner;
  for (let z = -len / 2 + 0.4; z < len / 2; z += 1.25){
    for (const sx of [-0.32, 0.32]) boxB(g, 0.08, 0.42, 0.08, C.navy, sx, 0, z, { r: 0.03 });
  }
  boxB(g, 0.8, 0.12, len, C.stone, 0, 0.42, 0, { r: 0.05 });
  boxB(g, 0.7, 0.04, len - 0.1, C.navy, 0, 0.54, 0, { r: 0.02 });
  for (const sx of [-0.43, 0.43]) boxB(g, 0.07, 0.14, len, C.teal, sx, 0.48, 0, { r: 0.03 });
  const n = 22;
  slats = new THREE.InstancedMesh(geo(0.62, 0.014, 0.07, 0.006), mat(0x3a4566), n);
  slats.receiveShadow = true;
  g.add(slats);
  slats.userData = { n, len };
}

/* ---------- FACTORY HALL (glass roof) ---------- */
{
  const p = prop(-4.0, BY, 3.6, 0.22);
  const g = p.inner;
  boxB(g, 5.4, FL, 6.2, C.white);
  boxB(g, 0.3, 2.6, 6.2, C.green, -2.55, 0, 0, { r: 0.1 });
  for (const z of [-2.95, 0, 2.95]) boxB(g, 0.22, 2.6, 0.22, C.white, 2.5, 0, z, { r: 0.07 });
  for (const x of [-1.25, 0.9]) boxB(g, 0.22, 2.6, 0.22, C.white, x, 0, 2.95, { r: 0.07 });
  boxB(g, 0.22, 2.6, 0.22, C.white, -2.5, 0, -2.95, { r: 0.07 });
  // roof ring
  for (const z of [-3.0, 3.0]) boxB(g, 5.4, 0.16, 0.18, C.white, 0, 2.6, z, { r: 0.05 });
  for (const x of [-2.6, 2.6]) boxB(g, 0.18, 0.16, 6.2, C.white, x, 2.6, 0, { r: 0.05 });
  // gabled glass roof
  const glass = mat(C.tealLight, { rough: 0.1, metal: 0.1, opacity: 0.32 });
  for (const s of [-1, 1]){
    const pane = box(g, 2.75, 0.05, 6.15, 0, s * 1.3, 2.98, 0, { r: 0.02, material: glass, cast: false });
    pane.rotation.z = -s * 0.2;
    for (const z of [-3.0, -1.5, 0, 1.5, 3.0]){
      const m = box(g, 2.75, 0.07, 0.08, C.white, s * 1.3, 3.0, z, { r: 0.03 });
      m.rotation.z = -s * 0.2;
    }
  }
  boxB(g, 0.16, 0.12, 6.2, C.white, 0, 3.2, 0, { r: 0.05 });
  // tool wall + benches
  for (const z of [-2.0, -0.6]) boxB(g, 0.5, 1.2, 0.9, C.teal, -2.15, FL, z, { r: 0.08 });
  boxB(g, 0.6, 0.6, 1.6, C.stone, -2.05, FL, 1.4, { r: 0.08 });
  // chip tray for the pick arm
  boxB(g, 0.7, 0.4, 0.7, C.navy, -1.6, FL, 2.0, { r: 0.08 });
  for (let i = 0; i < 3; i++) chipMesh(g, -1.6, FL + 0.4 + i * 0.065, 2.0);
}

const beltChips = [];
for (let k = 0; k < 8; k++){
  const p = prop(BELT_X, BELT_TOP, SPAWN_Z, 0.5);
  const c = chipMesh(p.inner);
  beltChips.push({ p, c, spawn: (k + 0.8) * STEP });
}


/* ---------- robotic arms ---------- */
const L1 = 0.8, L2 = 0.72, SHOULDER = BY + FL + 0.64;
function robotArm(x, z){
  const p = prop(x, BY + FL, z, 0.35);
  const base = p.inner;
  boxB(base, 0.62, 0.14, 0.62, C.navy);
  boxB(base, 0.42, 0.3, 0.42, C.white, 0, 0.14, 0, { r: 0.1 });
  const turret = new THREE.Group(); turret.position.y = 0.44; base.add(turret);
  boxB(turret, 0.38, 0.16, 0.38, C.teal, 0, 0, 0, { r: 0.07 });
  const sh = new THREE.Group(); sh.position.y = 0.2; turret.add(sh);
  box(sh, 0.24, 0.24, 0.3, C.teal, 0, 0, 0, { r: 0.09 });
  const upper = new THREE.Group(); sh.add(upper);
  box(upper, L1, 0.16, 0.18, C.white, L1 / 2, 0, 0, { r: 0.07 });
  const elbow = new THREE.Group(); elbow.position.x = L1; upper.add(elbow);
  box(elbow, 0.2, 0.2, 0.24, C.teal, 0, 0, 0, { r: 0.08 });
  const fore = new THREE.Group(); elbow.add(fore);
  box(fore, L2, 0.13, 0.15, C.white, L2 / 2, 0, 0, { r: 0.06 });
  const wrist = new THREE.Group(); wrist.position.x = L2; fore.add(wrist);
  box(wrist, 0.15, 0.15, 0.18, C.navy, 0, 0, 0, { r: 0.06 });
  box(wrist, 0.18, 0.08, 0.08, C.navy, 0.12, 0, 0, { r: 0.03 });
  for (const s of [-1, 1]) box(wrist, 0.1, 0.04, 0.04, C.navy, 0.24, 0, s * 0.07, { r: 0.015 });
  const tip = new THREE.Group(); tip.position.x = 0.29; wrist.add(tip);
  return { p, turret, upper, fore, wrist, tip, x, z };
}
function setArm(arm, tx, tz, h){
  const dx = tx - arm.x, dz = tz - arm.z;
  const r = Math.hypot(dx, dz);
  arm.turret.rotation.y = Math.atan2(-dz, dx);
  const d = Math.min(Math.hypot(r, h), L1 + L2 - 0.02);
  const e = Math.acos(Math.max(-1, Math.min(1, (d * d - L1 * L1 - L2 * L2) / (2 * L1 * L2))));
  const a = Math.atan2(h, r) + Math.atan2(L2 * Math.sin(e), L1 + L2 * Math.cos(e));
  arm.upper.rotation.z = a;
  arm.fore.rotation.z = -e;
  arm.wrist.rotation.z = -Math.PI / 2 - (a - e);
}
const H_DIP = (BELT_TOP + 0.1 + 0.3) - SHOULDER, H_HOVER = H_DIP + 0.45;
const armPick = robotArm(-5.0, 4.6);
const armScan = robotArm(-3.0, 3.2);
const armWeld = robotArm(-5.0, 1.6);
const heldChip = chipMesh(armPick.tip, 0.02, 0, 0); heldChip.rotation.z = Math.PI / 2; heldChip.position.x = 0.03;
const scanLight = box(armScan.tip, 0.06, 0.12, 0.12, 0, 0, 0, 0, { r: 0.03, material: glowMat(0xffffff, 0x2ee6d0, 0), cast: false });
const sparks = [];
for (let i = 0; i < 5; i++) sparks.push(box(armWeld.tip, 0.05, 0.05, 0.05, 0, 0.05, 0, 0, { r: 0.015, material: glowMat(0xffe1c4, C.orange, 3), cast: false }));
const TRAY = { x: -5.6, z: 5.6 };

/* ---------- cooling towers + pipes ---------- */
for (const [tx, tz] of [[2.1, -5.3], [4.7, -5.3]]){
  const p = prop(tx, BY, tz);
  const g = p.inner;
  let y = 0;
  for (const [w, h, c] of [[1.9, 0.25, C.stone], [1.75, 0.8, C.white], [1.55, 0.6, C.white], [1.45, 0.3, C.teal], [1.58, 0.55, C.white], [1.75, 0.22, C.teal]]){
    boxB(g, w, h, w, c, 0, y, 0, { r: Math.min(0.2, w * 0.12) }); y += h;
  }
  const f = new THREE.Group(); f.position.set(0, y + 0.03, 0); g.add(f);
  box(f, 1.3, 0.05, 0.18, C.navy, 0, 0, 0, { r: 0.02 });
  box(f, 0.18, 0.05, 1.3, C.navy, 0, 0, 0, { r: 0.02 });
  box(f, 0.26, 0.1, 0.26, C.stone, 0, 0.03, 0, { r: 0.05 });
  fans.push({ g: f, k: 7 });
  for (let i = 0; i < 5; i++){
    const m = new THREE.Mesh(geo(0.5, 0.5, 0.5, 0.2), new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.95, transparent: true, opacity: 0.8, depthWrite: false }));
    m.position.y = y; g.add(m);
    steam.push({ m, phase: i / 5, y0: y, seed: tx });
  }
}
{
  const p = prop(-0.2, BY, -5.3, 0.4);
  const g = p.inner;
  box(g, 2.9, 0.22, 0.22, C.stone, 0, 1.3, 0, { r: 0.1 });
  box(g, 2.9, 0.18, 0.18, C.teal, 0, 1.3, 0.42, { r: 0.08 });
  for (const x of [-1.0, 1.0]) boxB(g, 0.1, 1.3, 0.62, C.navy, x, 0, 0.2, { r: 0.03 });
}

/* ---------- solar array ---------- */
const solar = [];
for (const z of [-3.5, -2.55, -1.6]) for (const x of [1.35, 2.75, 4.15, 5.55]){
  const p = prop(x, BY, z);
  const g = p.inner;
  boxB(g, 0.08, 0.5, 0.08, C.navy, 0, 0, 0, { r: 0.03 });
  const piv = new THREE.Group(); piv.position.y = 0.55; g.add(piv);
  box(piv, 1.25, 0.05, 0.72, C.white, 0, 0, 0, { r: 0.02 });
  box(piv, 1.13, 0.03, 0.6, C.royal, 0, 0.03, 0, { r: 0.01, rough: 0.25, metal: 0.2 });
  box(piv, 0.02, 0.035, 0.6, C.white, 0, 0.035, 0, { r: 0.008, cast: false });
  solar.push(piv);
}

/* ---------- logistics hub with drone pads ---------- */
const HUB = { x: 3.3, z: 2.8, w: 4.6, d: 4.0, h: 2.2 };
const HUB_ROOF = BY + HUB.h + 0.18;
const pads = [{ x: HUB.x - 1.1, z: HUB.z - 0.2 }, { x: HUB.x + 1.1, z: HUB.z - 0.2 }];
let dish;
{
  const p = prop(HUB.x, BY, HUB.z, 0.25);
  const g = p.inner;
  boxB(g, HUB.w, HUB.h, HUB.d, C.teal, 0, 0, 0, { r: 0.14 });
  boxB(g, HUB.w + 0.14, 0.18, HUB.d + 0.14, C.tealDeep, 0, HUB.h, 0, { r: 0.06 });
  windows(g, { w: HUB.w, d: HUB.d, y0: 1.6, floors: 1, fh: 1, cols: 6, colsSide: 5, ww: 0.5, wh: 0.42 });
  for (const dx of [-0.9, 0.7]){
    boxB(g, 1.1, 1.15, 0.08, C.white, dx, 0, HUB.d / 2, { r: 0.03 });
    for (let y = 0.2; y < 1.1; y += 0.22) boxB(g, 1.0, 0.03, 0.04, C.stone, dx, y, HUB.d / 2 + 0.04, { r: 0.01, cast: false });
  }
  boxB(g, 0.08, 1.1, 1.0, C.white, HUB.w / 2, 0, 0.9, { r: 0.03 });
  for (const pd of pads){
    const lx = pd.x - HUB.x, lz = pd.z - HUB.z;
    boxB(g, 1.5, 0.06, 1.5, C.white, lx, HUB.h + 0.18, lz, { r: 0.03 });
    boxB(g, 1.15, 0.03, 1.15, C.royal, lx, HUB.h + 0.24, lz, { r: 0.02 });
    for (const [cx, cz] of [[-0.62, -0.62], [0.62, -0.62], [-0.62, 0.62], [0.62, 0.62]])
      boxB(g, 0.1, 0.06, 0.1, 0, lx + cx, HUB.h + 0.24, lz + cz, { r: 0.03, material: glowMat(0xffd2ad, C.orange, 0.8), cast: false });
  }
  dish = new THREE.Group(); dish.position.set(1.7, HUB.h + 0.18, 1.45); g.add(dish);
  boxB(dish, 0.12, 0.45, 0.12, C.navy, 0, 0, 0, { r: 0.04 });
  const d = box(dish, 0.62, 0.07, 0.62, C.white, 0.08, 0.58, 0, { r: 0.03 }); d.rotation.z = 0.7;
  box(dish, 0.05, 0.25, 0.05, C.navy, 0.18, 0.7, 0, { r: 0.02 });
}

/* ---------- drones ---------- */
function drone(){
  const g = new THREE.Group(), rotors = [];
  box(g, 0.46, 0.14, 0.46, C.white, 0, 0, 0, { r: 0.06 });
  box(g, 0.2, 0.05, 0.2, C.teal, 0, 0.09, 0, { r: 0.02 });
  for (const [ax, az] of [[1, 1], [1, -1], [-1, 1], [-1, -1]]){
    const arm = box(g, 0.5, 0.05, 0.06, C.navy, ax * 0.22, 0.02, az * 0.22, { r: 0.02 });
    arm.rotation.y = ax * az > 0 ? -Math.PI / 4 : Math.PI / 4;
    const r = new THREE.Group(); r.position.set(ax * 0.38, 0.08, az * 0.38); g.add(r);
    box(r, 0.42, 0.02, 0.07, C.tealLight, 0, 0, 0, { r: 0.008, cast: false });
    box(r, 0.07, 0.04, 0.07, C.navy, 0, 0, 0, { r: 0.02 });
    rotors.push(r);
  }
  for (const s of [-1, 1]) box(g, 0.04, 0.12, 0.44, C.navy, s * 0.16, -0.12, 0, { r: 0.015 });
  const pkg = new THREE.Group(); g.add(pkg);
  box(pkg, 0.02, 0.18, 0.02, C.navy, 0, -0.16, 0, { r: 0.008 });
  box(pkg, 0.3, 0.26, 0.3, C.orange, 0, -0.36, 0, { r: 0.05 });
  box(pkg, 0.31, 0.04, 0.31, C.white, 0, -0.3, 0, { r: 0.015, cast: false });
  return { g, rotors, pkg };
}
const drones = [
  { pad: pads[0], dest: new THREE.Vector3(11, 9.5, -9), off: 1.0 },
  { pad: pads[1], dest: new THREE.Vector3(-9, 9.5, 11), off: 6.0 }
].map(d => {
  const v = drone();
  const p = prop(d.pad.x, HUB_ROOF + 0.24, d.pad.z, 0.6);
  p.inner.add(v.g);
  return { ...d, ...v, p, P: new THREE.Vector3(d.pad.x, HUB_ROOF + 0.24 + 0.17, d.pad.z) };
});
const D_DEP = 0.6, D_ARR = 3.8, D_BACK = 4.6, D_LAND = 7.8, D_NEWPKG = 8.6;

/* ---------- AGVs between factory and hub ---------- */
const agvs = [5.35, 5.95].map((z, i) => {
  const p = prop(-1.4, BY, z, 0.5);
  const g = p.inner;
  boxB(g, 0.7, 0.18, 0.44, C.white, 0, 0.04, 0, { r: 0.07 });
  boxB(g, 0.6, 0.04, 0.36, C.teal, 0, 0.22, 0, { r: 0.015 });
  boxB(g, 0.06, 0.06, 0.3, 0, 0.35, 0.08, 0, { r: 0.02, material: glowMat(0xffffff, 0x2ee6d0, 0.9), cast: false });
  const crate = new THREE.Group(); g.add(crate);
  boxB(crate, 0.38, 0.3, 0.3, C.orange, 0, 0.26, 0, { r: 0.05 });
  return { p, crate, x0: -1.3, x1: i ? 4.0 : 2.4, off: i * 0.5 };
});

/* ---------- autonomous trucks ---------- */
function wheel(parent, x, y, z, r, side){
  const w = new THREE.Group(); w.position.set(x, y, z); parent.add(w);
  box(w, r * 2, r * 2, 0.14, C.tire, 0, 0, 0, { r: r * 0.45 });
  box(w, r * 0.9, r * 0.9, 0.04, C.stone, 0, 0, side * 0.07, { r: 0.02 });
  return w;
}
const lidars = [];
function truck(color, short){
  const g = new THREE.Group(), wheels = [], r = 0.18;
  const cargoL = short ? 1.0 : 1.55;
  box(g, cargoL + 0.75, 0.14, 0.78, C.navy, -0.05, 0.27, 0, { r: 0.05 });
  box(g, 0.72, 0.68, 0.86, C.white, cargoL / 2 + 0.3, 0.68, 0, { r: 0.16 });
  box(g, 0.06, 0.3, 0.74, C.glass, cargoL / 2 + 0.66, 0.78, 0, { r: 0.03, rough: 0.15, metal: 0.1 });
  for (const s of [-1, 1]) box(g, 0.36, 0.26, 0.04, C.glass, cargoL / 2 + 0.38, 0.8, s * 0.43, { r: 0.015, rough: 0.15 });
  box(g, cargoL, 0.92, 0.9, color, -0.25, 0.8, 0, { r: 0.12 });
  box(g, cargoL - 0.1, 0.06, 0.92, C.white, -0.25, 0.6, 0, { r: 0.02, cast: false });
  const lid = new THREE.Group(); lid.position.set(cargoL / 2 + 0.3, 1.08, 0); g.add(lid);
  box(lid, 0.16, 0.1, 0.16, C.navy, 0, 0, 0, { r: 0.04 });
  box(lid, 0.2, 0.06, 0.06, 0, 0, 0.07, 0, { r: 0.02, material: glowMat(0xffd2ad, C.orange, 0.7), cast: false });
  lidars.push(lid);
  for (const s of [-0.26, 0.26]) box(g, 0.04, 0.08, 0.14, C.white, cargoL / 2 + 0.67, 0.45, s, { r: 0.02, emissive: 0xfff3d6, ei: 0.5, cast: false });
  const xs = short ? [-0.55, cargoL / 2 + 0.3] : [-0.85, -0.42, cargoL / 2 + 0.3];
  for (const wx of xs) for (const wz of [-0.4, 0.4]) wheels.push(wheel(g, wx, r, wz, r, Math.sign(wz)));
  return { g, wheels, r };
}
const innerLane = makePath(8.1, 1.4), outerLane = makePath(9.9, 1.8);
const vehicles = [];
function addVehicle(v, path, rev, offset){
  const p = prop(0, RY, 0);
  p.inner.add(v.g);
  vehicles.push({ ...v, p, path, rev, offset, K: Math.max(1, Math.round(path.L / (TAU * v.r))) });
}
addVehicle(truck(C.royal), innerLane, false, 2);
addVehicle(truck(C.green, true), innerLane, false, 2 + innerLane.L / 3);
addVehicle(truck(C.white), innerLane, false, 2 + 2 * innerLane.L / 3);
addVehicle(truck(C.teal), outerLane, true, 6);
addVehicle(truck(C.royalDeep, true), outerLane, true, 6 + outerLane.L / 2);

/* ---------- engineers ---------- */
const walkers = [];
function addWalker(ax, az, bx, bz, vest, off = 0, laps = 1){
  const p = prop(ax, BY, az, 0.55);
  const e = engineer(vest); e.g.scale.setScalar(0.85); p.inner.add(e.g);
  walkers.push({ p, e, ax, az, bx, bz, off, laps });
}
addWalker(-0.4, -6.2, -0.4, 6.2, C.green, 0);
addWalker(-0.2, -0.3, 6.2, -0.3, C.tealLight, 0.35);
addWalker(-1.0, 6.6, 5.6, 6.6, C.greenLight, 0.6);
addWalker(-3.1, -2.6, -3.1, -5.8, C.tealLight, 0.2, 2);
const watcher = (() => {
  const p = prop(-2.1, BY + FL, 2.4, 0.55);
  const e = engineer(C.green); e.g.scale.setScalar(0.85); e.g.rotation.y = Math.PI; p.inner.add(e.g);
  e.arms[0].rotation.z = 1.2; e.arms[1].rotation.z = 1.2;
  box(e.g, 0.04, 0.2, 0.28, C.navy, 0.3, 0.6, 0, { r: 0.02 });
  return e;
})();

/* ---------- trees + lamps ---------- */
const trees = [];
function tree(x, z, y = 0, size = 1){
  const p = prop(x, y, z);
  const g = p.inner; g.scale.setScalar(size);
  boxB(g, 0.5, 0.12, 0.5, C.stone);
  boxB(g, 0.16, 0.8, 0.16, C.trunk, 0, 0.1, 0, { r: 0.05 });
  const fol = new THREE.Group(); fol.position.y = 0.8; g.add(fol);
  box(fol, 0.95, 0.85, 0.95, pick([C.green, C.greenDeep, C.teal]), 0, 0.42, 0, { r: 0.3 });
  box(fol, 0.66, 0.6, 0.66, pick([C.greenLight, C.green]), 0.08, 1.0, -0.05, { r: 0.22 });
  fol.rotation.y = rnd() * TAU;
  trees.push({ fol, ph: Math.floor(rnd() * 6) });
}
function lamp(x, z, rotY, y = 0){
  const p = prop(x, y, z);
  const g = p.inner; g.rotation.y = rotY;
  boxB(g, 0.28, 0.1, 0.28, C.navy, 0, 0, 0, { r: 0.04 });
  boxB(g, 0.09, 2.3, 0.09, C.navy, 0, 0.05, 0, { r: 0.03 });
  box(g, 0.62, 0.07, 0.07, C.navy, 0.28, 2.32, 0, { r: 0.02 });
  box(g, 0.36, 0.12, 0.22, C.navy, 0.56, 2.26, 0, { r: 0.05 });
  box(g, 0.28, 0.04, 0.16, C.white, 0.56, 2.19, 0, { r: 0.015, emissive: 0xfff1d0, ei: 0.9, cast: false });
}
const O = 11.9;
for (const u of [-9.5, -4.5, 1.5, 6.5]){ tree(u, -O); tree(-O, u); }
for (const u of [-8, -2.5, 3.5]){ tree(u, O, 0, 0.9); tree(O, u, 0, 0.9); }
tree(O, O, 0, 1.1); tree(-O, -O, 0, 1.2); tree(O, -O, 0, 1.05); tree(-O, O, 0, 1.05);
for (const u of [-6.5, 1.0, 6.0]){ lamp(u, 11.1, Math.PI / 2); lamp(11.1, u, 0); }
for (const u of [-6.5, 4.0]){ lamp(u, -11.1, -Math.PI / 2); lamp(-11.1, u, Math.PI); }
tree(6.65, -6.5, BY, 0.75); tree(6.65, -0.9, BY, 0.7); tree(6.7, 5.4, BY, 0.7);
lamp(6.85, 2.8, 0, BY); lamp(-6.95, 6.95, -Math.PI * 0.75, BY); lamp(0.4, -6.9, -Math.PI / 2, BY);

/* ---------- post-processing ---------- */
const rt = new THREE.WebGLRenderTarget(W, H, { type: THREE.HalfFloatType, samples: 4 });
const composer = new EffectComposer(renderer, rt);
composer.setPixelRatio(1);
composer.setSize(W, H);
composer.addPass(new RenderPass(scene, camera));
try {
  const gtao = new GTAOPass(scene, camera, W, H);
  gtao.output = GTAOPass.OUTPUT.Default;
  gtao.blendIntensity = 1.0;
  gtao.updateGtaoMaterial({ radius: 0.7, distanceExponent: 1.4, thickness: 1.2, scale: 1.15, samples: 12, distanceFallOff: 1, screenSpaceRadius: false });
  gtao.updatePdMaterial({ lumaPhi: 10, depthPhi: 2, normalPhi: 3, radius: 6, radiusExponent: 1, rings: 2, samples: 16 });
  composer.addPass(gtao);
} catch (e) { console.warn('GTAO unavailable', e); }
composer.addPass(new OutputPass());

/* ---------- overlay stats ---------- */
const elT = document.getElementById('sTok'), elG = document.getElementById('sGpu'), elM = document.getElementById('sMod'), elDM = document.getElementById('dMod');
const fmtInt = n => n.toLocaleString('en-US');
const ARR_OFF = mod(0.8 * STEP + CHIP_T, STEP);
const countSince = (t, first, period) => t < first ? 0 : Math.floor((t - first) / period) + 1;
let lastG = -1, lastM = -1, lastT = '', lastFly = -1;
function bump(el){ el.classList.remove('bump'); void el.offsetWidth; el.classList.add('bump'); }
function updateStats(t, lt){
  const tok = (48214e6 + t * 4.1e6) / 1e9;
  const ts = tok.toFixed(3) + 'B';
  if (ts !== lastT){ elT.textContent = ts; lastT = ts; }
  const g = 24576 + 8 * countSince(t, ARR_OFF, STEP);
  if (g !== lastG){ elG.textContent = fmtInt(g); if (lastG >= 0) bump(elG); lastG = g; }
  let m = 1207, fly = 0;
  for (const d of drones){
    m += countSince(t, d.off + D_DEP, LOOP);
    const u = mod(lt - d.off, LOOP);
    if (u >= D_DEP && u < D_LAND) fly++;
  }
  if (m !== lastM){ elM.textContent = fmtInt(m); if (lastM >= 0) bump(elM); lastM = m; }
  if (fly !== lastFly){ elDM.textContent = fly === 0 ? 'drones docked' : fly + (fly > 1 ? ' drones out' : ' drone out'); lastFly = fly; }
}

/* ---------- animation ---------- */
const bumpWin = (x, w) => Math.abs(x) < w ? 0.5 * (1 + Math.cos(Math.PI * x / w)) : 0;
function passOffset(lt, armZ){
  // seconds since the nearest chip crossed armZ (negative = still approaching)
  const age = (SPAWN_Z - armZ) / BELT_V;
  const u = mod(lt - 0.8 * STEP - age, STEP);
  return u > STEP / 2 ? u - STEP : u;
}

let start = null;
const card = document.querySelector('.card');
function restart(){
  start = null; buildDone = false;
  lastG = -1; lastM = -1; lastT = ''; lastFly = -1;
  card.style.animation = 'none'; void card.offsetWidth; card.style.animation = '';
}
addEventListener('keydown', e => { if (e.code === 'Space' || e.key === 'r' || e.key === 'R') { e.preventDefault(); restart(); } });
addEventListener('pointerdown', restart);

function frame(now){
  if (start === null) start = now;
  const t = (now - start) / 1000, lt = mod(t, LOOP), ph = lt / LOOP;
  applyBuild(t);

  // camera: eased sway-orbit with gentle push in, period = LOOP
  const az = Math.PI / 4 + 0.3 * Math.sin(ph * TAU);
  const push = (1 - Math.cos(ph * TAU)) / 2;
  const R = 124 - 10 * push, el = 0.58 + 0.03 * Math.sin(ph * TAU);
  camera.position.set(Math.sin(az) * Math.cos(el) * R, Math.sin(el) * R, Math.cos(az) * Math.cos(el) * R);
  camera.lookAt(0, 1.2, 0);

  // conveyor slats
  { const { n, len } = slats.userData;
    for (let i = 0; i < n; i++){
      const z = len / 2 - mod(i * (len / n) + lt * BELT_V, len);
      _m.makeTranslation(0, 0.585, z);
      slats.setMatrixAt(i, _m);
    }
    slats.instanceMatrix.needsUpdate = true; }

  // chips on the belt
  for (const ch of beltChips){
    const a = mod(lt - ch.spawn, LOOP);
    const on = a < CHIP_T;
    ch.c.visible = on;
    if (on) ch.p.root.position.z = SPAWN_Z - BELT_V * a;
  }

  // pick arm: tray -> belt every STEP
  { const u = mod(lt, STEP) / STEP;
    const toTray = smooth(u / 0.3) * (1 - smooth((u - 0.45) / 0.25));
    const tx = lerp(BELT_X, TRAY.x, toTray), tz = lerp(SPAWN_Z, TRAY.z, toTray);
    const dip = Math.max(bumpWin(u - 0.375, 0.075), bumpWin(u - 0.8, 0.1));
    setArm(armPick, tx, tz, lerp(H_HOVER, H_DIP, dip));
    heldChip.visible = u > 0.375 && u < 0.8; }

  // scan arm follows each chip as it passes
  { const d = passOffset(lt, armScan.z), w = bumpWin(d, 0.32);
    setArm(armScan, BELT_X, armScan.z - BELT_V * d * w, lerp(H_HOVER, H_DIP + 0.08, w));
    scanLight.material.emissiveIntensity = 3 * bumpWin(d, 0.14); }

  // weld arm + sparks
  { const d = passOffset(lt, armWeld.z), w = bumpWin(d, 0.32);
    setArm(armWeld, BELT_X, armWeld.z - BELT_V * d * w, lerp(H_HOVER, H_DIP, w));
    const on = Math.abs(d) < 0.16;
    sparks.forEach((s, i) => {
      s.visible = on;
      if (on){ const q = mod(lt * 9 + i * 0.21, 1); s.position.set(0.05 + q * 0.12, Math.sin(i * 2.4 + lt * 40) * 0.18 * q, Math.cos(i * 1.7 + lt * 37) * 0.18 * q); s.scale.setScalar(1 - q * 0.7); }
    }); }

  // racks light up in a wave each time a chip is ingested
  { const age = mod(lt - ARR_OFF, STEP);
    for (const r of racks){
      const wave = Math.exp(-Math.pow((age - r.delay) / 0.12, 2));
      r.led.emissiveIntensity = 0.35 + 2.2 * wave;
      r.dot.emissiveIntensity = Math.sin(ph * TAU * r.blink * 3 + r.ph) > 0.2 ? 2.4 : 0.15;
    } }

  // drones
  for (const d of drones){
    const u = mod(lt - d.off, LOOP);
    let pos = d.P.clone(), vis = true, s = 1, tilt = 0;
    if (u >= D_DEP && u < D_BACK + (D_LAND - D_BACK)){
      let k;
      if (u < D_ARR) k = (u - D_DEP) / (D_ARR - D_DEP);
      else if (u < D_BACK) { k = 1; vis = false; }
      else k = 1 - (u - D_BACK) / (D_LAND - D_BACK);
      const hk = smooth((k - 0.12) / 0.88);
      pos.x = lerp(d.P.x, d.dest.x, hk); pos.z = lerp(d.P.z, d.dest.z, hk);
      pos.y = lerp(d.P.y, d.dest.y, easeOutCubic(k / 0.55));
      s = 1 - smooth((k - 0.7) / 0.3);
      tilt = 0.25 * Math.sin(Math.PI * hk) * (u < D_ARR ? 1 : -1);
    }
    d.p.root.position.copy(pos);
    d.p.root.rotation.y = Math.atan2(-(d.dest.z - d.P.z), d.dest.x - d.P.x);
    d.g.rotation.z = -tilt;
    d.g.visible = vis && s > 0.01;
    d.g.scale.setScalar(Math.max(0.001, s));
    d.g.position.y = (u < D_DEP || u > D_LAND) ? 0 : 0.03 * Math.sin(lt * 20);
    d.rotors.forEach((r, i) => (r.rotation.y = ph * TAU * (60 + i)));
    const pkgOn = u < D_ARR || u >= D_NEWPKG;
    d.pkg.visible = pkgOn;
    if (pkgOn) d.pkg.scale.setScalar(u >= D_NEWPKG ? Math.max(0.001, easeOutBack(clamp01((u - D_NEWPKG) / 0.4))) : 1);
  }

  // AGVs shuttle crates factory -> hub
  for (const a of agvs){
    const q = mod(ph + a.off, 1), f = (1 - Math.cos(q * TAU)) / 2;
    a.p.root.position.x = lerp(a.x0, a.x1, f);
    a.p.root.rotation.y = Math.sin(q * TAU) >= 0 ? 0 : Math.PI;
    a.crate.visible = Math.sin(q * TAU) >= 0;
  }

  // trucks
  for (const v of vehicles){
    const pt = v.path.at(v.offset + ph * v.path.L, v.rev);
    v.p.root.position.set(pt.x, RY, pt.z);
    v.p.root.rotation.y = pt.yaw;
    const spin = -ph * TAU * v.K;
    v.wheels.forEach(w => (w.rotation.z = spin));
  }
  lidars.forEach((l, i) => (l.rotation.y = ph * TAU * (20 + i)));

  // engineers walk back and forth
  for (const w of walkers){
    const q = mod(ph * w.laps + w.off, 1), f = (1 - Math.cos(q * TAU)) / 2, dir = Math.sin(q * TAU);
    w.p.root.position.set(lerp(w.ax, w.bx, f), BY, lerp(w.az, w.bz, f));
    const dx = (w.bx - w.ax) * Math.sign(dir || 1), dz = (w.bz - w.az) * Math.sign(dir || 1);
    w.p.root.rotation.y = Math.atan2(-dz, dx);
    const amp = Math.min(1, Math.abs(dir) * 2.5);
    const sw = Math.sin(ph * TAU * 22) * 0.55 * amp;
    w.e.legs[0].rotation.z = sw; w.e.legs[1].rotation.z = -sw;
    w.e.arms[0].rotation.z = -sw * 0.6; w.e.arms[1].rotation.z = sw * 0.6;
    w.e.g.position.y = Math.abs(Math.sin(ph * TAU * 22)) * 0.035 * amp;
  }
  watcher.head.rotation.z = -0.25 + 0.08 * Math.sin(ph * TAU * 4);
  watcher.head.rotation.y = 0.3 * Math.sin(ph * TAU * 2);

  // ambient
  for (const tr of trees){ tr.fol.rotation.z = 0.035 * Math.sin(ph * TAU * 2 + tr.ph); tr.fol.rotation.x = 0.025 * Math.cos(ph * TAU * 2 + tr.ph); }
  fans.forEach((f, i) => (f.g.rotation.y = ph * TAU * (f.k + i)));
  blinkers.forEach(b => (b.material.emissiveIntensity = mod(lt, 1) < 0.35 ? 2.2 : 0));
  solar.forEach((s, i) => (s.rotation.x = -0.38 + 0.08 * Math.sin(ph * TAU + i * 0.15)));
  dish.rotation.y = 0.6 * Math.sin(ph * TAU);
  for (const st of steam){
    const u = mod(ph * 3 + st.phase, 1);
    st.m.position.set(Math.sin(u * TAU + st.phase * 9) * 0.2 + u * 0.5, st.y0 + 0.2 + u * 2.6, Math.cos(u * 5 + st.phase * 4 + st.seed) * 0.18);
    st.m.scale.setScalar(0.4 + u * 1.3);
    st.m.material.opacity = 0.85 * Math.sin(u * Math.PI);
  }

  updateStats(t, lt);
  composer.render();
  requestAnimationFrame(frame);
}
window.__sceneOK = true;
requestAnimationFrame(frame);
</script>
</body>
</html>
canh-3d-video-doc/05-xuyen-mai-van-phong-nimbus.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
</head>
<body>
<title>Nimbus HQ Xuyên Mái</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,800&family=Manrope:wght@500;600;700;800&display=swap">
<style>
/* Layout: fixed 1088x1920 frame scaled to fit the window; frosted card floats over the top third, diorama sits low. */
:root{
  --bg:#e9ecf1;
  --frame:#f6f7f9;
  --ink:#141b38;
  --muted:#5a6383;
  --accent:#ff7a1c;
  --royal:#2f55e6;
  --teal:#17a99c;
  --green:#3db86a;
  --f-display:'Bricolage Grotesque','Manrope',system-ui,sans-serif;
  --f-body:'Manrope',system-ui,-apple-system,'Segoe UI',sans-serif;
  color-scheme:light;
}
html,body{height:100%;margin:0;overflow:hidden;background:var(--bg);color:var(--ink)}
#stage{
  position:absolute;left:50%;top:50%;
  width:1088px;height:1920px;
  transform:translate(-50%,-50%) scale(var(--s,0.4));
  transform-origin:center center;
  overflow:hidden;background:var(--frame);
}
#c{position:absolute;inset:0;display:block;width:1088px;height:1920px}
.vignette{position:absolute;inset:0;pointer-events:none;
  background:radial-gradient(120% 80% at 50% 60%, rgba(255,255,255,0) 55%, rgba(20,27,56,.07) 100%)}

.card{
  position:absolute;left:84px;right:84px;top:132px;
  padding:42px 48px 44px;
  border-radius:44px;
  background:linear-gradient(160deg, rgba(255,255,255,.62), rgba(255,255,255,.34));
  -webkit-backdrop-filter:blur(26px) saturate(1.5);
  backdrop-filter:blur(26px) saturate(1.5);
  border:1.5px solid rgba(255,255,255,.85);
  box-shadow:0 30px 80px -30px rgba(20,27,56,.35), inset 0 1px 0 rgba(255,255,255,.9);
  font-family:var(--f-body);
  opacity:0;transform:translateY(-24px) scale(.98);
  animation:cardIn .7s cubic-bezier(.2,.9,.25,1.15) .55s forwards;
}
@keyframes cardIn{to{opacity:1;transform:none}}
.head{display:flex;align-items:center;justify-content:space-between;gap:24px}
.brand{display:flex;align-items:center;gap:22px}
.mark{width:68px;height:68px;border-radius:22px;background:var(--accent);position:relative;
  box-shadow:0 10px 24px -8px rgba(255,122,28,.7)}
.mark::before{content:"";position:absolute;left:16px;top:27px;width:36px;height:24px;border-radius:6px;background:#fff}
.mark::after{content:"";position:absolute;left:26px;top:17px;width:8px;height:7px;border:4px solid #fff;border-bottom:0;border-radius:6px 6px 0 0}
h1{margin:0;font-family:var(--f-display);font-weight:800;font-size:56px;line-height:1;letter-spacing:-.02em;text-wrap:balance}
h1 span{color:var(--muted);font-weight:600}
.sub{margin:10px 0 0;font-size:22px;font-weight:600;color:var(--muted);letter-spacing:.01em}
.live{display:flex;align-items:center;gap:12px;padding:12px 20px;border-radius:999px;
  background:rgba(20,27,56,.9);color:#fff;font-weight:800;font-size:20px;letter-spacing:.16em}
.live i{width:14px;height:14px;border-radius:50%;background:var(--accent);box-shadow:0 0 0 0 rgba(255,122,28,.7);animation:pulse 1s ease-out infinite}
@keyframes pulse{0%{box-shadow:0 0 0 0 rgba(255,122,28,.75)}100%{box-shadow:0 0 0 16px rgba(255,122,28,0)}}
.stats{display:grid;grid-template-columns:1fr 1.25fr 1fr;gap:0;margin-top:36px;
  border-top:1.5px solid rgba(20,27,56,.09)}
.stat{padding:30px 0 0 28px;display:flex;flex-direction:column;gap:10px;min-width:0;border-left:1.5px solid rgba(20,27,56,.09)}
.stat:first-child{padding-left:0;border-left:0}
.label{font-size:19px;font-weight:800;text-transform:uppercase;letter-spacing:.14em;color:var(--muted);display:flex;align-items:center;gap:10px}
.label b{width:12px;height:12px;border-radius:4px;display:inline-block}
.val{font-family:var(--f-body);font-weight:800;font-size:66px;line-height:1;letter-spacing:-.03em;
  font-variant-numeric:tabular-nums;color:var(--ink);display:inline-block;transform-origin:left bottom}
.val.bump{animation:bump .55s ease-out}
@keyframes bump{0%{color:var(--accent);transform:translateY(-6px) scale(1.04)}100%{color:var(--ink);transform:none}}
.delta{font-size:20px;font-weight:700;color:var(--teal);font-variant-numeric:tabular-nums}
@media (prefers-reduced-motion: reduce){.card{animation-duration:.01s}.live i{animation:none}}
</style>

<div id="stage">
  <canvas id="c" width="1088" height="1920"></canvas>
  <div class="vignette"></div>
  <section class="card" aria-label="Nimbus HQ live ops">
    <div class="head">
      <div class="brand">
        <div class="mark" aria-hidden="true"></div>
        <div>
          <h1>Nimbus HQ <span>· Live Ops</span></h1>
          <p class="sub">Floor 1 · open plan · today</p>
        </div>
      </div>
      <div class="live"><i></i>LIVE</div>
    </div>
    <div class="stats">
      <div class="stat">
        <span class="label"><b style="background:var(--royal)"></b>Tasks done</span>
        <span class="val" id="sOrders">1,284</span>
        <span class="delta" id="dOrders">8 in review</span>
      </div>
      <div class="stat">
        <span class="label"><b style="background:var(--accent)"></b>Closed today</span>
        <span class="val" id="sRev">$184,200</span>
        <span class="delta" id="dRev">12 deals · avg $15.4k</span>
      </div>
      <div class="stat">
        <span class="label"><b style="background:var(--green)"></b>Coffees</span>
        <span class="val" id="sDel">212</span>
        <span class="delta">pantry · floor 1</span>
      </div>
    </div>
  </section>
</div>

<div id="err" hidden style="position:fixed;left:16px;right:16px;bottom:16px;padding:14px 16px;border-radius:12px;background:#141b38;color:#fff;font:600 14px/1.4 Manrope,system-ui,sans-serif;z-index:9"></div>
<script>
(function(){
  var el=document.getElementById('err');
  function show(m){ el.hidden=false; el.textContent='Không chạy được cảnh 3D: '+m; }
  window.addEventListener('error',function(e){ show(e.message||'lỗi tải script'); },true);
  window.addEventListener('unhandledrejection',function(e){ show(String(e.reason&&e.reason.message||e.reason)); });
  setTimeout(function(){ if(!window.__sceneOK) show('thư viện Three.js chưa tải xong sau 15 giây (mạng hoặc CDN bị chặn).'); },15000);
})();
</script>
<script type="importmap">
{ "imports": {
  "three": "https://cdn.jsdelivr.net/npm/three@0.160.0/+esm"
} }
</script>

<script type="module">
import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.160.0/+esm';
import { RoundedBoxGeometry } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/geometries/RoundedBoxGeometry.js/+esm';
import { EffectComposer } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/EffectComposer.js/+esm';
import { RenderPass } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/RenderPass.js/+esm';
import { GTAOPass } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/GTAOPass.js/+esm';
import { OutputPass } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/OutputPass.js/+esm';

const W = 1088, H = 1920, LOOP = 10, TAU = Math.PI * 2;

/* ---------- fit frame to window ---------- */
const stage = document.getElementById('stage');
function fit(){ stage.style.setProperty('--s', Math.min(innerWidth / W, innerHeight / H)); }
addEventListener('resize', fit); fit();

/* ---------- palette ---------- */
const C = {
  ground:0xf7f6f2, base:0x2a48d4, road:0xd2d7e0, walk:0xe6e9ee, line:0xffffff,
  royal:0x2f55e6, royalDeep:0x2340b8, teal:0x17a99c, tealLight:0x93e0d6,
  green:0x3db86a, greenDeep:0x22864a, greenLight:0x92dba6,
  orange:0xff7a1c, white:0xffffff, navy:0x1d2547, tire:0x2b3040, glass:0xcdeef4,
  trunk:0x8d847b, stone:0xc9ced8,
  skin:[0xf2cba8,0xdba57e,0xae7652,0x7d5136], hair:[0x2b2420,0x5a3b25,0x1d2547,0xd9b77a]
};

/* ---------- seeded random ---------- */
function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296}}
const rnd = mulberry32(11);
const pick = arr => arr[Math.floor(rnd() * arr.length)];
const clamp01 = x => Math.min(1, Math.max(0, x));
const smooth = x => { x = clamp01(x); return x * x * (3 - 2 * x); };
const easeOutCubic = x => 1 - Math.pow(1 - x, 3);
const mod = (a, n) => ((a % n) + n) % n;
const easeOutBack = x => { const c1 = 2.1, c3 = c1 + 1; return 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2); };

/* ---------- renderer ---------- */
const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('c'), antialias: true, powerPreference: 'high-performance' });
renderer.setPixelRatio(1);
renderer.setSize(W, H, false);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;

const scene = new THREE.Scene();
scene.background = new THREE.Color(0xf7f8fa);

const camera = new THREE.PerspectiveCamera(32, W / H, 0.4, 320);
camera.setViewOffset(W, H, 0, -300, W, H); // drop the diorama below the card

/* ---------- lights ---------- */
scene.add(new THREE.HemisphereLight(0xeef3ff, 0xd8d3c8, 1.35));
const sun = new THREE.DirectionalLight(0xfff4e6, 2.7);
sun.position.set(-12, 26, 14);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
Object.assign(sun.shadow.camera, { left:-20, right:20, top:20, bottom:-20, near:1, far:80 });
sun.shadow.bias = -0.0004;
sun.shadow.normalBias = 0.025;
sun.shadow.radius = 5;
scene.add(sun);

/* ---------- geometry + material helpers ---------- */
const geoCache = new Map(), matCache = new Map();
function geo(w, h, d, r){
  r = r ?? Math.min(0.14, Math.min(w, h, d) * 0.22);
  r = Math.min(r, Math.min(w, h, d) / 2 - 0.001);
  const k = [w, h, d, r].map(v => v.toFixed(3)).join('|');
  if (!geoCache.has(k)) geoCache.set(k, new RoundedBoxGeometry(w, h, d, 2, r));
  return geoCache.get(k);
}
function mat(color, o = {}){
  const k = [color, o.rough, o.metal, o.emissive, o.ei, o.opacity].join('|');
  if (!matCache.has(k)) matCache.set(k, new THREE.MeshStandardMaterial({
    color, roughness: o.rough ?? 0.62, metalness: o.metal ?? 0,
    emissive: o.emissive ?? 0x000000, emissiveIntensity: o.ei ?? 1,
    transparent: o.opacity !== undefined, opacity: o.opacity ?? 1
  }));
  return matCache.get(k);
}
function box(parent, w, h, d, color, x = 0, y = 0, z = 0, o = {}){
  const m = new THREE.Mesh(geo(w, h, d, o.r), o.material || mat(color, o));
  m.position.set(x, y, z);
  m.castShadow = o.cast !== false;
  m.receiveShadow = true;
  parent.add(m);
  return m;
}
// bottom-aligned box
const boxB = (p, w, h, d, c, x, y, z, o) => box(p, w, h, d, c, x, y + h / 2, z, o);

/* ---------- build-in system ---------- */
const builds = [];
function prop(x, y, z, delay){
  const root = new THREE.Group(); root.position.set(x, y, z);
  const inner = new THREE.Group(); root.add(inner);
  scene.add(root);
  const dist = Math.hypot(x, z);
  builds.push({ inner, delay: delay ?? (0.16 + (dist / 18) * 0.5 + rnd() * 0.12) });
  return { root, inner };
}
let buildDone = false;
function applyBuild(t){
  if (buildDone) return;
  let all = true;
  for (const b of builds){
    const x = clamp01((t - b.delay) / 0.42);
    if (x < 1) all = false;
    b.inner.visible = x > 0;
    b.inner.scale.setScalar(Math.max(0.001, easeOutBack(x)));
    b.inner.position.y = -1.6 * (1 - easeOutCubic(x));
  }
  if (all) buildDone = true;
}

/* ---------- lane path: rounded rectangle, arc-length param ---------- */
function makePath(h, rc){
  const a = 2 * (h - rc), arc = Math.PI * rc / 2, L = 4 * a + 4 * arc, k = h - rc;
  const starts = [[-k, h], [h, k], [k, -h], [-h, -k]];
  const dirs = [[1, 0], [0, -1], [-1, 0], [0, 1]];
  const centers = [[k, k], [k, -k], [-k, -k], [-k, k]];
  const th0 = [Math.PI / 2, 0, -Math.PI / 2, -Math.PI];
  return { L, at(s, rev){
    if (rev) s = L - s;
    s = ((s % L) + L) % L;
    const seg = a + arc, i = Math.min(3, Math.floor(s / seg)), r = s - i * seg;
    let x, z, dx, dz;
    if (r < a){ x = starts[i][0] + dirs[i][0] * r; z = starts[i][1] + dirs[i][1] * r; dx = dirs[i][0]; dz = dirs[i][1]; }
    else { const th = th0[i] - (r - a) / rc; x = centers[i][0] + rc * Math.cos(th); z = centers[i][1] + rc * Math.sin(th); dx = Math.sin(th); dz = -Math.cos(th); }
    if (rev){ dx = -dx; dz = -dz; }
    return { x, z, yaw: Math.atan2(-dz, dx) };
  } };
}

/* ======================================================================
   WORLD
   ====================================================================== */
const ROAD_IN = 6.4, ROAD_OUT = 10.6, BY = 0.22, RY = 0.06;

// slab
{
  const p = prop(0, 0, 0, 0);
  box(p.inner, 26, 1.0, 26, C.ground, 0, -0.5, 0, { r: 0.45 });
  box(p.inner, 25.2, 0.42, 25.2, C.base, 0, -1.12, 0, { r: 0.2, cast: false });
}
// road + markings
{
  const p = prop(0, 0, 0, 0.06);
  box(p.inner, ROAD_OUT * 2, RY, ROAD_OUT * 2, C.road, 0, RY / 2, 0, { r: 0.03, cast: false });
  const h = 8.65, rc = 1.4;
  for (let side = 0; side < 4; side++){
    for (let u = -h + rc + 0.7; u < h - rc - 0.5; u += 1.3){
      const m = box(p.inner, 0.62, 0.02, 0.1, C.line, 0, RY + 0.01, 0, { r: 0.009, cast: false });
      if (side === 0) m.position.set(u, m.position.y, h);
      if (side === 1) { m.position.set(h, m.position.y, u); m.rotation.y = Math.PI / 2; }
      if (side === 2) m.position.set(u, m.position.y, -h);
      if (side === 3) { m.position.set(-h, m.position.y, u); m.rotation.y = Math.PI / 2; }
    }
  }
  // teal bike-lane line
  const bl = 7.3;
  for (const s of [1, -1]){
    box(p.inner, bl * 2 - 1.6, 0.02, 0.07, C.teal, 0, RY + 0.01, s * bl, { r: 0.009, cast: false });
    box(p.inner, 0.07, 0.02, bl * 2 - 1.6, C.teal, s * bl, RY + 0.01, 0, { r: 0.009, cast: false });
  }
  // crosswalks
  for (let z = ROAD_IN + 0.35; z < ROAD_OUT - 0.2; z += 0.62) box(p.inner, 1.4, 0.02, 0.32, C.line, -0.6, RY + 0.012, z, { r: 0.009, cast: false });
  for (let x = ROAD_IN + 0.35; x < ROAD_OUT - 0.2; x += 0.62) box(p.inner, 0.32, 0.02, 1.4, C.line, x, RY + 0.012, -0.6, { r: 0.009, cast: false });
}
// block sidewalk
{
  const p = prop(0, 0, 0, 0.1);
  box(p.inner, ROAD_IN * 2, BY, ROAD_IN * 2, C.walk, 0, BY / 2, 0, { r: 0.08 });
}

/* ---------- window grids (instanced) ---------- */
const _m = new THREE.Matrix4(), _q = new THREE.Quaternion(), _s = new THREE.Vector3(1, 1, 1), _v = new THREE.Vector3();
function windows(parent, { w, d, y0, floors, fh, cols, colsSide, ww = 0.5, wh = 0.62, color = C.glass }){
  const list = [];
  for (let f = 0; f < floors; f++){
    const y = y0 + f * fh;
    for (let c = 0; c < cols; c++) list.push([(c - (cols - 1) / 2) * (w / cols), y, d / 2, 0]);
    for (let c = 0; c < colsSide; c++) list.push([w / 2, y, (c - (colsSide - 1) / 2) * (d / colsSide), Math.PI / 2]);
  }
  const im = new THREE.InstancedMesh(geo(ww, wh, 0.1, 0.035), mat(color, { rough: 0.18, metal: 0.15 }), list.length);
  list.forEach(([x, y, z, ry], i) => {
    _q.setFromAxisAngle(_v.set(0, 1, 0), ry);
    _m.compose(new THREE.Vector3(x, y, z), _q, _s);
    im.setMatrixAt(i, _m);
  });
  im.castShadow = true; im.receiveShadow = true;
  parent.add(im);
  return im;
}

const fans = [], blinkers = [];
function building({ x, z, w, d, h, color, trim, cols, colsSide }){
  const p = prop(x, BY, z);
  const g = p.inner;
  boxB(g, w, h, d, color, 0, 0, 0, { r: 0.14 });
  boxB(g, w + 0.14, 0.18, d + 0.14, trim, 0, h, 0, { r: 0.06 });
  // storefront band
  boxB(g, w * 0.86, 0.72, 0.1, C.glass, 0, 0.18, d / 2, { r: 0.04, rough: 0.2 });
  boxB(g, 0.1, 0.72, d * 0.86, C.glass, w / 2, 0.18, 0, { r: 0.04, rough: 0.2 });
  boxB(g, w + 0.06, 0.12, d + 0.06, trim, 0, 1.05, 0, { r: 0.04 });
  const fh = 1.05, floors = Math.floor((h - 1.6) / fh);
  windows(g, { w, d, y0: 1.75, floors, fh, cols, colsSide });
  return { p, g, h };
}

// Tower (royal blue)
{
  const b = building({ x: -3.0, z: -3.0, w: 5.0, d: 5.0, h: 9.6, color: C.royal, trim: C.royalDeep, cols: 4, colsSide: 4 });
  // water tank
  const tg = new THREE.Group(); tg.position.set(-1.0, b.h + 0.18, -0.8); b.g.add(tg);
  for (const [lx, lz] of [[-0.35, -0.35], [0.35, -0.35], [-0.35, 0.35], [0.35, 0.35]]) boxB(tg, 0.08, 0.5, 0.08, C.navy, lx, 0, lz, { r: 0.02 });
  boxB(tg, 1.0, 0.9, 1.0, C.tealLight, 0, 0.5, 0, { r: 0.3 });
  boxB(tg, 1.08, 0.12, 1.08, C.teal, 0, 1.4, 0, { r: 0.05 });
  // antenna + blinking light
  boxB(b.g, 0.08, 1.8, 0.08, C.navy, 1.2, b.h + 0.18, 1.0, { r: 0.03 });
  const bl = boxB(b.g, 0.2, 0.2, 0.2, C.white, 1.2, b.h + 1.95, 1.0, { r: 0.08, material: new THREE.MeshStandardMaterial({ color: 0xffffff, emissive: 0x7ff3e4, emissiveIntensity: 0 }) });
  blinkers.push(bl);
  boxB(b.g, 1.4, 0.5, 0.9, C.stone, 1.0, b.h + 0.18, -1.2, { r: 0.12 });
}
// Mid-rise (green) with AC fans
{
  const b = building({ x: 3.25, z: -3.2, w: 4.6, d: 4.6, h: 6.1, color: C.green, trim: C.greenDeep, cols: 4, colsSide: 4 });
  for (const [ax, az] of [[-1.0, -0.9], [0.4, -0.9], [-1.0, 0.6]]){
    boxB(b.g, 1.0, 0.5, 1.0, C.stone, ax, b.h + 0.18, az, { r: 0.12 });
    const f = new THREE.Group(); f.position.set(ax, b.h + 0.71, az); b.g.add(f);
    box(f, 0.8, 0.04, 0.14, C.navy, 0, 0, 0, { r: 0.02 });
    box(f, 0.14, 0.04, 0.8, C.navy, 0, 0, 0, { r: 0.02 });
    fans.push(f);
  }
  boxB(b.g, 0.6, 0.9, 0.6, C.white, 1.3, b.h + 0.18, 1.2, { r: 0.12 });
}
// Low-rise (teal) with roof garden
{
  const b = building({ x: -3.2, z: 3.0, w: 4.4, d: 4.4, h: 4.7, color: C.teal, trim: 0x0f877d, cols: 3, colsSide: 3 });
  for (const [gx, gz] of [[-1.2, -1.1], [0, -1.1], [1.2, -1.1], [-1.2, 0.4], [1.2, 0.4]]){
    boxB(b.g, 0.8, 0.3, 0.8, C.white, gx, b.h + 0.18, gz, { r: 0.08 });
    boxB(b.g, 0.62, 0.42, 0.62, pick([C.green, C.greenLight, C.greenDeep]), gx, b.h + 0.42, gz, { r: 0.18 });
  }
}

/* ---------- the office: cutaway interior ---------- */
const SHOP = { x: 2.7, z: 2.7 };
const steam = [];
let barista = null;
const IN = { svc0: 0.6, step: 1.25 };            // a task completes every 1.25 s (8 per loop)
const MEET = { t0: 1.0, period: 5, note: 1.8, cheer: 2.0 };
const RUN = { period: 5, refill: 0.6 };
const DESK_H = 0.48, BAR_Y = 0.66;
const off = { workers: [], screens: [], badges: [], bars: [], notes: [], aud: [], steam: [] };
function glowLike(color){ return new THREE.MeshStandardMaterial({ color, emissive: color, emissiveIntensity: 0.25, roughness: 0.5 }); }
function mugMesh(parent, x = 0, y = 0, z = 0){
  const c = new THREE.Group(); c.position.set(x, y, z); parent.add(c);
  boxB(c, 0.1, 0.12, 0.1, C.white, 0, 0, 0, { r: 0.03 });
  boxB(c, 0.11, 0.035, 0.11, C.orange, 0, 0.05, 0, { r: 0.015, cast: false });
  box(c, 0.03, 0.06, 0.03, C.white, 0.065, 0.06, 0, { r: 0.012 });
  return c;
}
{
  const p = prop(SHOP.x, BY, SHOP.z, 0.22);
  const g = p.inner;
  const s = 3.8, half = s / 2;
  off.g = g;
  boxB(g, s + 0.1, 0.12, s + 0.1, C.white, 0, 0, 0, { r: 0.05 });
  boxB(g, s - 0.2, 0.012, s - 0.2, 0xe4e9f1, 0, 0.12, 0, { r: 0.005, cast: false });
  boxB(g, 2.2, 0.012, 2.3, C.tealLight, 0.6, 0.128, 0.75, { r: 0.005, cast: false });
  // back walls (cutaway: front two sides open)
  boxB(g, s, 1.55, 0.18, C.white, 0, 0.12, -half + 0.09, { r: 0.05 });
  boxB(g, 0.18, 1.55, s, C.white, -half + 0.09, 0.12, 0, { r: 0.05 });
  boxB(g, s - 0.2, 0.3, 0.04, C.tealLight, 0.1, 0.12, -half + 0.2, { r: 0.015 });
  boxB(g, 0.04, 0.3, s - 0.2, C.tealLight, -half + 0.2, 0.12, 0.1, { r: 0.015 });
  boxB(g, s + 0.06, 0.1, 0.24, C.royal, 0, 1.67, -half + 0.09, { r: 0.04 });
  boxB(g, 0.24, 0.1, s + 0.06, C.royal, -half + 0.09, 1.67, 0, { r: 0.04 });
  // front corner post + header beams
  boxB(g, 0.2, 1.65, 0.2, C.white, half - 0.1, 0.12, half - 0.1, { r: 0.06 });
  boxB(g, 0.12, 0.1, s, C.royal, half - 0.06, 1.67, 0, { r: 0.04 });
  boxB(g, s, 0.1, 0.12, C.royal, 0, 1.67, half - 0.06, { r: 0.04 });
  boxB(g, 0.5, 0.16, 0.06, 0, 0.9, 1.47, half - 0.02, { r: 0.04, material: glowLike(C.orange) });
  // low front planter walls, door gap at the front-left and side gap on the right
  { const x0 = -0.55, x1 = 1.7, w = x1 - x0;
    boxB(g, w, 0.28, 0.14, C.white, (x0 + x1) / 2, 0.12, half - 0.08, { r: 0.05 });
    boxB(g, w - 0.1, 0.12, 0.1, C.green, (x0 + x1) / 2, 0.4, half - 0.08, { r: 0.05 }); }
  for (const [z0, z1] of [[-1.75, -0.25], [1.05, 1.7]]){ const d = z1 - z0; boxB(g, 0.14, 0.28, d, C.white, half - 0.08, 0.12, (z0 + z1) / 2, { r: 0.05 }); boxB(g, 0.1, 0.12, d - 0.1, C.green, half - 0.08, 0.4, (z0 + z1) / 2, { r: 0.05 }); }
  for (const x of [-1.62, -0.78]) boxB(g, 0.08, 1.4, 0.12, C.teal, x, 0.12, half - 0.06, { r: 0.03 });
  boxB(g, 0.92, 0.1, 0.12, C.teal, -1.2, 1.5, half - 0.06, { r: 0.03 });

  // wall screen with a live bar chart (no text)
  const scrX = 0.25, scrZ = -half + 0.2;
  boxB(g, 1.7, 0.88, 0.06, C.navy, scrX, 0.55, scrZ, { r: 0.04 });
  box(g, 0.5, 0.035, 0.02, C.white, scrX - 0.45, 1.3, scrZ + 0.04, { r: 0.01, cast: false });
  box(g, 0.26, 0.03, 0.02, C.stone, scrX - 0.57, 1.24, scrZ + 0.04, { r: 0.01, cast: false });
  box(g, 0.06, 0.06, 0.02, 0, scrX + 0.7, 1.3, scrZ + 0.04, { r: 0.02, material: glowLike(C.orange), cast: false });
  box(g, 1.4, 0.012, 0.02, C.panel, scrX, BAR_Y - 0.01, scrZ + 0.04, { r: 0.004, cast: false });
  for (let i = 0; i < 8; i++){
    const col = i === 7 ? C.orange : (i % 2 ? C.teal : C.green);
    const m = new THREE.Mesh(geo(0.12, 1, 0.03, 0.012), glowLike(col));
    m.position.set(scrX - 0.665 + i * 0.19, BAR_Y + 0.1, scrZ + 0.045);
    g.add(m);
    off.bars.push({ m, i, base: 0.14 + 0.045 * i + (i % 3) * 0.03 });
  }

  // whiteboard on the side wall: three columns of sticky notes
  const wbX = -half + 0.2, wbZ = -0.5;
  boxB(g, 0.05, 0.78, 1.5, C.white, wbX, 0.52, wbZ, { r: 0.03 });
  box(g, 0.08, 0.04, 1.5, C.stone, wbX + 0.04, 0.54, wbZ, { r: 0.015 });
  for (const dz of [-0.25, 0.25]) box(g, 0.02, 0.64, 0.015, C.stone, wbX + 0.03, 0.92, wbZ + dz, { r: 0.006, cast: false });
  const noteCols = [[-0.5, [C.tealLight, C.royal, C.tealLight]], [0, [C.teal, C.tealLight]], [0.5, [C.greenLight]]];
  for (const [cz, cols] of noteCols) cols.forEach((c, r) => box(g, 0.02, 0.14, 0.16, c, wbX + 0.035, 1.12 - r * 0.2, wbZ + cz, { r: 0.01, cast: false }));
  for (let k = 0; k < 2; k++) off.notes.push(box(g, 0.02, 0.14, 0.16, C.orange, wbX + 0.04, 0.92 - k * 0.2, wbZ + 0.5, { r: 0.01, cast: false }));
  // stand-up meeting at the board
  { const pr = person(C.royal); pr.g.scale.setScalar(0.85); pr.g.position.set(-1.45, 0.12, -1.3);
    pr.g.rotation.y = Math.atan2(-0.8, 0.5); g.add(pr.g); off.presenter = pr; }
  for (const [x, z, c] of [[-0.95, -0.72, C.green], [-0.85, -0.08, C.tealLight]]){
    const pr = person(c); pr.g.scale.setScalar(0.85); pr.g.position.set(x, 0.12, z);
    pr.g.rotation.y = Math.atan2(-(wbZ - z), (wbX - x)); g.add(pr.g); off.aud.push(pr);
  }
  // tall plants
  for (const [px, pz] of [[-0.85, -1.6], [-1.58, 0.8]]){
    boxB(g, 0.34, 0.3, 0.34, C.white, px, 0.12, pz, { r: 0.08 });
    boxB(g, 0.4, 0.5, 0.4, C.green, px, 0.42, pz, { r: 0.17 });
    boxB(g, 0.28, 0.32, 0.28, C.greenDeep, px + 0.04, 0.88, pz - 0.03, { r: 0.12 });
  }

  // desk pod: four workstations with people typing
  const spots = [[0.15, 0.25], [1.05, 0.25], [0.15, 1.15], [1.05, 1.15]];
  const shirtsO = [C.royal, C.green, C.navy, C.teal];
  spots.forEach(([dx, dz], i) => {
    for (const lx of [-0.34, 0.34]) boxB(g, 0.05, 0.36, 0.36, C.navy, dx + lx, 0.12, dz, { r: 0.02 });
    boxB(g, 0.8, 0.04, 0.44, C.white, dx, DESK_H, dz, { r: 0.02 });
    boxB(g, 0.14, 0.02, 0.09, C.navy, dx, DESK_H + 0.04, dz - 0.12, { r: 0.008 });
    boxB(g, 0.03, 0.12, 0.03, C.navy, dx, DESK_H + 0.05, dz - 0.14, { r: 0.01 });
    boxB(g, 0.46, 0.28, 0.04, C.navy, dx, DESK_H + 0.16, dz - 0.13, { r: 0.02 });
    const scrM = new THREE.MeshStandardMaterial({ color: 0xd8f5f1, emissive: 0x2ee6d0, emissiveIntensity: 0.35, roughness: 0.35 });
    box(g, 0.4, 0.22, 0.01, 0, dx, DESK_H + 0.30, dz - 0.105, { r: 0.004, material: scrM, cast: false });
    for (let r = 0; r < 3; r++){ const w = 0.24 - r * 0.06; box(g, w, 0.022, 0.006, r === 1 ? C.teal : C.navy, dx - 0.17 + w / 2, DESK_H + 0.36 - r * 0.05, dz - 0.098, { r: 0.003, cast: false }); }
    box(g, 0.28, 0.02, 0.09, C.stone, dx - 0.02, DESK_H + 0.05, dz + 0.08, { r: 0.008, cast: false });
    box(g, 0.06, 0.02, 0.09, C.stone, dx + 0.2, DESK_H + 0.05, dz + 0.08, { r: 0.008, cast: false });
    if (i % 2 === 0) mugMesh(g, dx + 0.3, DESK_H + 0.04, dz - 0.02);
    else { boxB(g, 0.1, 0.08, 0.1, C.white, dx + 0.3, DESK_H + 0.04, dz - 0.04, { r: 0.03 }); boxB(g, 0.13, 0.12, 0.13, C.green, dx + 0.3, DESK_H + 0.11, dz - 0.04, { r: 0.05 }); }
    // chair + seated worker facing the screen
    const ch = new THREE.Group(); ch.position.set(dx, 0.12, dz + 0.42); g.add(ch);
    boxB(ch, 0.3, 0.03, 0.3, C.navy, 0, 0, 0, { r: 0.01 });
    boxB(ch, 0.06, 0.2, 0.06, C.navy, 0, 0.02, 0, { r: 0.02 });
    boxB(ch, 0.32, 0.06, 0.3, C.royalDeep, 0, 0.22, 0, { r: 0.03 });
    boxB(ch, 0.3, 0.34, 0.05, C.royalDeep, 0, 0.28, 0.16, { r: 0.03 });
    const pr = person(shirtsO[i]);
    pr.g.scale.setScalar(0.82); pr.g.rotation.y = Math.PI / 2;
    pr.legs.forEach(l => (l.rotation.z = Math.PI / 2.2));
    ch.add(pr.g);
    off.workers.push({ pr, ch });
    off.screens.push(scrM);
    // "task done" check badge that pops above the monitor
    const bd = new THREE.Group(); bd.position.set(dx, DESK_H + 0.55, dz - 0.13); g.add(bd);
    box(bd, 0.2, 0.2, 0.05, 0, 0, 0, 0, { r: 0.06, material: glowLike(C.green), cast: false });
    const a = box(bd, 0.06, 0.024, 0.02, C.white, -0.035, -0.012, 0.03, { r: 0.008, cast: false }); a.rotation.z = -0.8;
    const b = box(bd, 0.11, 0.024, 0.02, C.white, 0.022, 0.012, 0.03, { r: 0.008, cast: false }); b.rotation.z = 0.9;
    bd.visible = false;
    off.badges.push(bd);
  });

  // pantry corner: counter, coffee machine, cups
  boxB(g, 0.6, 0.42, 0.42, C.teal, 1.45, 0.12, -1.6, { r: 0.05 });
  boxB(g, 0.64, 0.04, 0.46, C.white, 1.45, 0.54, -1.6, { r: 0.02 });
  { const cm = new THREE.Group(); cm.position.set(1.38, 0.58, -1.66); g.add(cm);
    boxB(cm, 0.3, 0.36, 0.26, C.stone, 0, 0, 0, { r: 0.06, metal: 0.4, rough: 0.3 });
    boxB(cm, 0.22, 0.06, 0.04, C.navy, 0, 0.24, 0.13, { r: 0.015 });
    boxB(cm, 0.1, 0.05, 0.08, C.navy, 0, 0.14, 0.15, { r: 0.015 });
    off.machineLed = box(cm, 0.05, 0.05, 0.02, 0, 0.08, 0.3, 0.135, { r: 0.012, material: glowLike(C.orange), cast: false }); }
  for (let k = 0; k < 3; k++) boxB(g, 0.09, 0.06, 0.09, C.white, 1.64, 0.58 + k * 0.06, -1.55, { r: 0.02 });
  for (let i = 0; i < 5; i++){
    const m = new THREE.Mesh(geo(0.12, 0.12, 0.12, 0.05), new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.95, transparent: true, opacity: 0, depthWrite: false }));
    g.add(m); off.steam.push({ m, phase: i / 5 });
  }
  // coffee runner
  { const pr = person(C.greenLight); pr.g.scale.setScalar(0.85); g.add(pr.g);
    pr.mug = mugMesh(pr.arms[0], 0, -0.36, 0); off.runner = pr; }
}

/* ---------- ground-floor glass shell + upper floors ("lid") that blow open during the dive ---------- */
const shell = new THREE.Group(), lid = new THREE.Group();
off.g.add(shell); off.g.add(lid);
{
  const g = shell, s = 3.8, half = s / 2;
  boxB(g, s - 0.16, 1.3, s - 0.16, C.glass, 0, 0.12, 0, { r: 0.06, rough: 0.12, metal: 0.1, opacity: 0.4, cast: false });
  for (let k = 0; k < 6; k++){ const u = -half + 0.35 + k * ((s - 0.7) / 5);
    boxB(g, 0.08, 1.3, 0.08, C.white, u, 0.12, half - 0.05, { r: 0.03 });
    boxB(g, 0.08, 1.3, 0.08, C.white, half - 0.05, 0.12, u, { r: 0.03 }); }
  boxB(g, 1.1, 0.07, 0.7, C.teal, -1.2, 1.32, half + 0.3, { r: 0.03 });
  for (const x of [-1.65, -0.75]) boxB(g, 0.05, 1.2, 0.05, C.navy, x, 0.12, half + 0.6, { r: 0.02 });
}
{
  const g = lid, s = 3.8, half = s / 2, FLOORS = 3, FH = 0.98;
  for (let f = 0; f < FLOORS; f++){
    const y0 = 1.42 + f * FH;
    boxB(g, s + 0.12, 0.14, s + 0.12, C.white, 0, y0, 0, { r: 0.05 });
    boxB(g, s - 0.06, FH - 0.14, s - 0.06, 0xa9d6e6, 0, y0 + 0.14, 0, { r: 0.06, rough: 0.12, metal: 0.25 });
    for (let k = 0; k < 7; k++){ const u = -half + 0.27 + k * ((s - 0.54) / 6);
      boxB(g, 0.07, FH - 0.14, 0.06, C.white, u, y0 + 0.14, half - 0.02, { r: 0.02 });
      boxB(g, 0.06, FH - 0.14, 0.07, C.white, half - 0.02, y0 + 0.14, u, { r: 0.02 }); }
  }
  const top = 1.42 + FLOORS * FH;
  boxB(g, s + 0.16, 0.18, s + 0.16, C.royal, 0, top, 0, { r: 0.06 });
  // orange brand plaque (abstract mark, no text)
  boxB(g, 0.62, 0.5, 0.06, C.orange, 1.15, top - 0.66, half + 0.03, { r: 0.08, emissive: C.orange, ei: 0.12 });
  boxB(g, 0.24, 0.24, 0.03, C.white, 1.15, top - 0.53, half + 0.07, { r: 0.06 });
  // roof kit: AC units with fans, a garden, a beacon
  for (const [ax, az] of [[-1.0, -1.0], [0.2, -1.0]]){
    boxB(g, 0.95, 0.42, 0.95, C.stone, ax, top + 0.18, az, { r: 0.12 });
    const f = new THREE.Group(); f.position.set(ax, top + 0.62, az); g.add(f);
    box(f, 0.75, 0.04, 0.13, C.navy, 0, 0, 0, { r: 0.02 });
    box(f, 0.13, 0.04, 0.75, C.navy, 0, 0, 0, { r: 0.02 });
    fans.push(f);
  }
  for (const [gx, gz] of [[0.4, 0.6], [1.2, 0.6], [0.4, 1.35], [1.2, 1.35]]){
    boxB(g, 0.7, 0.24, 0.7, C.white, gx, top + 0.18, gz, { r: 0.08 });
    boxB(g, 0.55, 0.32, 0.55, pick([C.green, C.greenLight, C.greenDeep]), gx, top + 0.38, gz, { r: 0.18 });
  }
  boxB(g, 0.07, 1.1, 0.07, C.navy, -1.3, top + 0.18, 1.2, { r: 0.03 });
  blinkers.push(boxB(g, 0.18, 0.18, 0.18, 0, -1.3, top + 1.28, 1.2, { r: 0.07, material: new THREE.MeshStandardMaterial({ color: 0xffffff, emissive: C.orange, emissiveIntensity: 0 }) }));
}
const OPEN = { shell0: 5.7, shell1: 6.3, lid0: 6.0, lid1: 6.9 };
function animateOpen(t){
  const a = clamp01((t - OPEN.shell0) / (OPEN.shell1 - OPEN.shell0));
  shell.visible = a < 1;
  shell.scale.setScalar(Math.max(0.001, 1 - a * a));
  shell.position.y = -0.4 * a;
  const b = clamp01((t - OPEN.lid0) / (OPEN.lid1 - OPEN.lid0));
  lid.visible = b < 1;
  const pre = Math.sin(clamp01(b / 0.18) * Math.PI) * 0.06;
  lid.scale.set(1 + pre, 1 - pre, 1 + pre);
  const lift = b < 0.18 ? 0 : Math.pow((b - 0.18) / 0.82, 2);
  lid.position.y = lift * 12;
  lid.rotation.x = lift * 0.5; lid.rotation.z = -lift * 0.35;
  if (b > 0.18) lid.scale.setScalar(Math.max(0.001, 1 - lift * 0.85));
}

/* ---------- one-shot camera: wide build-up -> dive -> close-up ---------- */
// [time, targetX, targetY, targetZ, R, elevation, azimuth, fov, viewOffsetY]
const Q = Math.PI / 4;
const CAMK = [
  [0.0, 0, 1.2, 0, 140, 0.64, Q - 0.30, 32, -190],
  [4.0, 0, 1.2, 0, 122, 0.58, Q + 0.05, 32, -190],
  [5.6, 1.9, 1.0, 1.9, 42, 0.98, Q + 0.18, 34, -230],
  [6.6, 2.7, 0.7, 2.7, 10, 1.30, Q + 0.24, 40, -280],
  [7.4, 2.7, 0.6, 2.7, 6.8, 1.02, Q + 0.14, 45, -300],
  [8.8, 2.7, 0.7, 2.7, 10.5, 0.55, Q, 45, -300]
];
const camLog = CAMK.map(k => k.map((v, j) => (j === 4 ? Math.log(v) : v)));
function camAt(t){
  const K = camLog, n = K.length;
  if (t >= K[n - 1][0]) return K[n - 1].slice();
  let i = 0; while (t > K[i + 1][0]) i++;
  const t0 = K[i][0], t1 = K[i + 1][0], h = t1 - t0, u = (t - t0) / h;
  const h00 = 2*u*u*u - 3*u*u + 1, h10 = u*u*u - 2*u*u + u, h01 = -2*u*u*u + 3*u*u, h11 = u*u*u - u*u;
  const tan = (k, j) => (k === 0 || k === n - 1) ? 0 : (K[k + 1][j] - K[k - 1][j]) / (K[k + 1][0] - K[k - 1][0]);
  const out = [t];
  for (let j = 1; j < K[0].length; j++) out.push(h00 * K[i][j] + h10 * h * tan(i, j) + h01 * K[i + 1][j] + h11 * h * tan(i + 1, j));
  return out;
}
let lastFov = 0, lastOff = 1e9;
function placeCamera(t){
  const c = camAt(t);
  let [, tx, ty, tz, lr, el, az, fov, off] = c;
  let R = Math.exp(lr);
  const end = CAMK[CAMK.length - 1][0];
  if (t > end){ const d = t - end, e = smooth(d / 1.5); az += 0.16 * Math.sin(d * 0.55) * e; R -= 0.8 * (1 - Math.cos(d * 0.5)) * 0.5 * e; }
  camera.position.set(tx + Math.sin(az) * Math.cos(el) * R, ty + Math.sin(el) * R, tz + Math.cos(az) * Math.cos(el) * R);
  camera.lookAt(tx, ty, tz);
  if (Math.abs(fov - lastFov) > 1e-3 || Math.abs(off - lastOff) > 1e-2){
    camera.fov = fov; camera.setViewOffset(W, H, 0, off, W, H); camera.updateProjectionMatrix();
    lastFov = fov; lastOff = off;
  }
}

// coffee runner keyframes over one 5 s cycle: [time, x, z]
const RUNK = [[0, 1.45, -1.2], [0.9, 1.45, -1.2], [1.2, 1.62, -0.85], [2.4, 1.62, 1.4], [3.4, 1.62, 1.4], [4.6, 1.62, -0.85], [4.9, 1.45, -1.2], [5.0, 1.45, -1.2]];
function keyAt(keys, t){
  if (t <= keys[0][0]) return { v: keys[0], a: keys[0], b: keys[0], f: 0 };
  for (let i = 0; i < keys.length - 1; i++){
    const a = keys[i], b = keys[i + 1];
    if (t <= b[0]){ const f = smooth((t - a[0]) / (b[0] - a[0])); return { v: a.map((x, j) => x + (b[j] - x) * f), a, b, f }; }
  }
  const l = keys[keys.length - 1]; return { v: l, a: l, b: l, f: 1 };
}
function animateShop(lt){
  // desk pod: typing, swivel, task-done badge + fist pump
  const tick0 = IN.svc0 + 0.5;
  const kLast = Math.floor((lt - tick0) / IN.step);
  off.workers.forEach((w, i) => {
    let age = 99;
    if (kLast >= 0){ const k = kLast - mod(kLast - i, 4); if (k >= 0) age = lt - (tick0 + k * IN.step); }
    const bd = off.badges[i];
    bd.visible = age < 1.3;
    if (bd.visible){
      const sc = easeOutBack(clamp01(age / 0.3)) * (1 - smooth((age - 0.9) / 0.4));
      bd.scale.setScalar(Math.max(0.001, sc));
      bd.position.y = DESK_H + 0.55 + age * 0.22;
    }
    off.screens[i].emissiveIntensity = age < 0.45 ? 1.5 : 0.35;
    const pump = age < 0.6 ? Math.sin(clamp01(age / 0.6) * Math.PI) : 0;
    w.pr.arms[0].rotation.z = 1.25 + 0.1 * Math.sin(lt * 31 + i) + pump * 1.5;
    w.pr.arms[1].rotation.z = 1.25 + 0.1 * Math.sin(lt * 29 + i * 2);
    w.ch.rotation.y = 0.1 * Math.sin(lt * 0.9 + i * 1.7);
  });

  // stand-up at the whiteboard: talk, add a note, cheer
  const r = mod(lt - MEET.t0, MEET.period);
  const talk = r < MEET.cheer ? 1 : 0;
  const reach = bumpWin(r - MEET.note, 0.35);
  const pr = off.presenter;
  pr.arms[1].rotation.z = 1.1 + 0.35 * Math.sin(lt * 6) * talk + 1.2 * reach;
  pr.arms[0].rotation.z = 0.25 + 0.2 * Math.sin(lt * 4.5) * talk;
  const cheer = r >= MEET.cheer && r < MEET.cheer + 0.7 ? Math.sin((r - MEET.cheer) / 0.7 * Math.PI) : 0;
  pr.g.position.y = 0.12 + 0.06 * cheer;
  off.aud.forEach((a, j) => {
    const c = j === 0 ? cheer : (r >= MEET.cheer + 0.08 && r < MEET.cheer + 0.78 ? Math.sin((r - MEET.cheer - 0.08) / 0.7 * Math.PI) : 0);
    a.arms[0].rotation.z = 0.15 + 2.6 * c + 0.06 * Math.sin(lt * 2 + j);
    a.arms[1].rotation.z = 0.15 + 2.6 * c;
    a.g.position.y = 0.12 + 0.12 * c;
  });
  off.notes.forEach((n, k) => {
    const popT = MEET.t0 + MEET.note + k * MEET.period;
    const sc = lt < popT ? 0 : easeOutBack(clamp01((lt - popT) / 0.35)) * (1 - smooth((lt - 9.7) / 0.3));
    n.visible = sc > 0.01;
    n.scale.setScalar(Math.max(0.001, sc));
  });

  // wall chart: bars breathe, the orange bar steps up with every closed deal
  const dealT = MEET.t0 + MEET.cheer;
  const deals = lt < dealT ? 0 : Math.floor((lt - dealT) / MEET.period) + 1;
  const dealAge = deals ? lt - (dealT + (deals - 1) * MEET.period) : 0;
  for (const b of off.bars){
    let h = b.base + 0.035 * Math.sin(lt * 1.3 + b.i * 0.9);
    if (b.i === 7) h = 0.2 + (deals ? 0.13 * (deals - 1 + easeOutBack(clamp01(dealAge / 0.4))) : 0) - 0.06 * smooth((lt - 9.7) / 0.3) * deals;
    h = Math.max(0.03, h);
    b.m.scale.y = h; b.m.position.y = BAR_Y + h / 2;
  }

  // coffee runner: refill -> walk to the window -> sip -> walk back
  const u = mod(lt, RUN.period);
  const kk = keyAt(RUNK, u), R = off.runner;
  R.g.position.set(kk.v[1], 0.12, kk.v[2]);
  const dx = kk.b[1] - kk.a[1], dz = kk.b[2] - kk.a[2];
  const moving = Math.hypot(dx, dz) > 0.05 && kk.f > 0 && kk.f < 1;
  R.g.rotation.y = moving ? Math.atan2(-dz, dx) : (u < 1.5 || u > 4.5 ? Math.PI / 2 : 0);
  const sw = moving ? Math.sin(lt * 22) * 0.5 : 0;
  R.legs[0].rotation.z = sw; R.legs[1].rotation.z = -sw;
  R.g.position.y = 0.12 + (moving ? Math.abs(Math.sin(lt * 22)) * 0.03 : 0);
  const sip = u >= 2.4 && u < 3.4 ? Math.sin((u - 2.4) / 1.0 * Math.PI) : 0;
  R.arms[0].rotation.z = u < 0.9 ? 1.25 : 0.9 + 1.0 * sip;
  R.arms[1].rotation.z = -sw * 0.5;
  const brewing = u >= 0.1 && u < 0.9 ? 1 : 0;
  off.machineLed.material.emissiveIntensity = brewing ? (mod(lt, 0.3) < 0.15 ? 2.2 : 0.4) : 0.25;
  for (const st of off.steam){
    const q = mod(lt * 1.6 + st.phase, 1);
    st.m.position.set(1.38 + Math.sin(q * 6 + st.phase * 9) * 0.04, 0.92 + q * 0.5, -1.56 + Math.cos(q * 5) * 0.03);
    st.m.scale.setScalar(0.5 + q * 1.2);
    st.m.material.opacity = brewing * 0.75 * Math.sin(q * Math.PI);
  }
}
const bumpWin = (x, w) => Math.abs(x) < w ? 0.5 * (1 + Math.cos(Math.PI * x / w)) : 0;

/* ---------- people ---------- */
function person(shirt, o = {}){
  const g = new THREE.Group();
  const skin = o.skin ?? pick(C.skin), pants = o.pants ?? pick([C.navy, 0x3a4566, 0x5d6a86]), hair = pick(C.hair);
  const legs = [];
  for (const sz of [-0.075, 0.075]){
    const lg = new THREE.Group(); lg.position.set(0, 0.34, sz);
    box(lg, 0.12, 0.34, 0.11, pants, 0, -0.17, 0, { r: 0.04 });
    g.add(lg); legs.push(lg);
  }
  box(g, 0.22, 0.38, 0.32, shirt, 0, 0.53, 0, { r: 0.08 });
  if (o.apron) box(g, 0.04, 0.3, 0.26, C.orange, 0.12, 0.5, 0, { r: 0.015 });
  const arms = [];
  for (const sz of [-0.2, 0.2]){
    const ag = new THREE.Group(); ag.position.set(0, 0.68, sz);
    box(ag, 0.1, 0.3, 0.08, shirt, 0, -0.14, 0, { r: 0.035 });
    g.add(ag); arms.push(ag);
  }
  box(g, 0.2, 0.2, 0.2, skin, 0, 0.84, 0, { r: 0.07 });
  box(g, 0.22, 0.08, 0.22, hair, -0.01, 0.96, 0, { r: 0.035 });
  return { g, legs, arms };
}
const shirts = [C.royal, C.teal, C.green, C.white, C.navy, C.tealLight, C.greenLight, C.royalDeep];

// queue path (world coords on block sidewalk)
const QP = [[6.05, 6.15], [5.6, 5.3], [4.9, 5.3], [4.2, 5.3], [3.5, 5.3], [2.8, 5.3], [2.15, 5.25], [1.5, 4.75], [1.5, 4.75]];
const QN = 8, STEP = IN.step;
const queue = [];
for (let k = 0; k < 0; k++){
  const p = prop(QP[k][0], BY, QP[k][1]);
  const pr = person(shirts[k % shirts.length]);
  pr.g.scale.setScalar(0.85);
  p.inner.add(pr.g);
  // a few carry an orange cup
  queue.push({ p, pr, k });
}

// café tables with sipping customers on the side sidewalk
const sippers = [];
for (const [tx, tz, ph] of []){
  const p = prop(tx, BY, tz);
  const g = p.inner;
  boxB(g, 0.08, 1.4, 0.08, C.navy, 0, 0, 0, { r: 0.03 });
  const um = boxB(g, 1.5, 0.1, 1.5, C.orange, 0, 1.4, 0, { r: 0.05 });
  boxB(g, 0.7, 0.06, 0.7, C.white, 0, 0.5, 0, { r: 0.03 });
  boxB(g, 0.06, 0.5, 0.06, C.navy, 0, 0, 0, { r: 0.02 });
  boxB(g, 0.16, 0.16, 0.16, C.white, 0.12, 0.56, 0.12, { r: 0.04 });
  for (const sz of [-0.55, 0.55]){
    boxB(g, 0.36, 0.3, 0.36, C.teal, 0, 0, sz, { r: 0.06 });
    const pr = person(pick(shirts));
    pr.g.scale.setScalar(0.82);
    pr.g.position.set(0, 0.06, sz);
    pr.g.rotation.y = sz > 0 ? Math.PI / 2 : -Math.PI / 2;
    pr.legs.forEach(l => (l.rotation.z = Math.PI / 2.2));
    g.add(pr.g);
    const cupM = box(pr.arms[0], 0.12, 0.14, 0.12, C.white, 0, -0.3, 0, { r: 0.04 });
    box(cupM, 0.13, 0.05, 0.13, C.orange, 0, 0, 0, { r: 0.02 });
    sippers.push({ pr, ph: ph + (sz > 0 ? 0.25 : 0) });
  }
}

/* ---------- vehicles ---------- */
function wheel(parent, x, y, z, r, side){
  const w = new THREE.Group(); w.position.set(x, y, z); parent.add(w);
  box(w, r * 2, r * 2, 0.14, C.tire, 0, 0, 0, { r: r * 0.45 });
  box(w, r * 0.9, r * 0.9, 0.04, C.stone, 0, 0, side * 0.07, { r: 0.02 });
  return w;
}
function car(color){
  const g = new THREE.Group(), wheels = [];
  box(g, 1.5, 0.4, 0.82, color, 0, 0.38, 0, { r: 0.15 });
  box(g, 0.86, 0.34, 0.74, C.glass, -0.1, 0.72, 0, { r: 0.12, rough: 0.18, metal: 0.1 });
  box(g, 0.82, 0.07, 0.72, color, -0.1, 0.9, 0, { r: 0.03 });
  for (const s of [-0.26, 0.26]){
    box(g, 0.05, 0.09, 0.16, C.white, 0.75, 0.42, s, { r: 0.02, emissive: 0xfff3d6, ei: 0.5, cast: false });
    box(g, 0.05, 0.09, 0.16, C.navy, -0.75, 0.42, s, { r: 0.02, cast: false });
  }
  for (const wx of [-0.48, 0.48]) for (const wz of [-0.38, 0.38]) wheels.push(wheel(g, wx, 0.17, wz, 0.17, Math.sign(wz)));
  return { g, wheels, r: 0.17 };
}
function bus(color){
  const g = new THREE.Group(), wheels = [];
  box(g, 3.0, 0.95, 0.95, color, 0, 0.66, 0, { r: 0.18 });
  box(g, 2.7, 0.34, 0.98, C.glass, -0.05, 0.86, 0, { r: 0.08, rough: 0.18 });
  box(g, 0.06, 0.5, 0.8, C.glass, 1.49, 0.8, 0, { r: 0.03, rough: 0.18 });
  box(g, 2.9, 0.08, 0.9, C.white, 0, 1.16, 0, { r: 0.03 });
  box(g, 0.8, 0.18, 0.6, C.white, -0.4, 1.28, 0, { r: 0.06 });
  for (const wx of [-1.0, 1.0]) for (const wz of [-0.44, 0.44]) wheels.push(wheel(g, wx, 0.2, wz, 0.2, Math.sign(wz)));
  return { g, wheels, r: 0.2 };
}
function scooter(){
  const g = new THREE.Group(), wheels = [];
  box(g, 0.66, 0.16, 0.26, C.white, 0, 0.3, 0, { r: 0.06 });
  box(g, 0.24, 0.24, 0.26, C.teal, 0.26, 0.42, 0, { r: 0.07 });
  box(g, 0.07, 0.42, 0.07, C.navy, 0.34, 0.6, 0, { r: 0.025 });
  box(g, 0.06, 0.05, 0.42, C.navy, 0.34, 0.82, 0, { r: 0.02 });
  box(g, 0.3, 0.08, 0.24, C.navy, -0.1, 0.44, 0, { r: 0.03 });
  box(g, 0.38, 0.36, 0.38, C.orange, -0.34, 0.68, 0, { r: 0.07, emissive: C.orange, ei: 0.08 });
  // rider
  box(g, 0.22, 0.36, 0.3, C.royal, -0.04, 0.68, 0, { r: 0.08 });
  for (const sz of [-0.13, 0.13]){ const a = box(g, 0.34, 0.08, 0.08, C.royal, 0.14, 0.76, sz, { r: 0.03 }); a.rotation.z = -0.4; }
  box(g, 0.2, 0.18, 0.2, pick(C.skin), -0.02, 0.96, 0, { r: 0.07 });
  box(g, 0.26, 0.14, 0.26, C.teal, -0.03, 1.08, 0, { r: 0.1 });
  for (const wx of [-0.3, 0.32]) wheels.push(wheel(g, wx, 0.14, 0, 0.14, 1));
  return { g, wheels, r: 0.14 };
}

const innerLane = makePath(7.75, 1.4), outerLane = makePath(9.55, 1.8), bikeLane = makePath(6.88, 1.0);
const vehicles = [];
function addVehicle(v, path, rev, offset){
  const p = prop(0, RY, 0);
  p.inner.add(v.g);
  vehicles.push({ ...v, p, path, rev, offset, K: Math.max(1, Math.round(path.L / (TAU * v.r))) });
}
[C.royal, C.white, C.teal].forEach((c, i) => addVehicle(car(c), innerLane, false, i * innerLane.L / 3 + 3));
addVehicle(bus(C.green), outerLane, true, 0);
[C.royalDeep, C.tealLight].forEach((c, i) => addVehicle(car(c), outerLane, true, (i + 1) * outerLane.L / 3));

// scooters parked at the shop curb, leave on a delivery lap and come back
const k0 = 6.88 - 1.0;
const scooters = [
  { s0: 4.25 + k0, dep: 1.5, dur: 7.0 },
  { s0: 3.35 + k0, dep: 3.0, dur: 7.0 }
].map(sc => {
  const v = scooter();
  const p = prop(0, RY, 0);
  p.inner.add(v.g);
  return { ...sc, ...v, p, K: Math.round(bikeLane.L / (TAU * v.r)) };
});

/* ---------- street furniture ---------- */
const trees = [];
function tree(x, z, y = 0, size = 1){
  const p = prop(x, y, z);
  const g = p.inner; g.scale.setScalar(size);
  boxB(g, 0.5, 0.12, 0.5, C.stone, 0, 0, 0, { r: 0.05 });
  boxB(g, 0.16, 0.8, 0.16, C.trunk, 0, 0.1, 0, { r: 0.05 });
  const fol = new THREE.Group(); fol.position.y = 0.8; g.add(fol);
  const c1 = pick([C.green, C.greenDeep, C.teal]);
  box(fol, 0.95, 0.85, 0.95, c1, 0, 0.42, 0, { r: 0.3 });
  box(fol, 0.66, 0.6, 0.66, pick([C.greenLight, C.green]), 0.08, 1.0, -0.05, { r: 0.22 });
  fol.rotation.y = rnd() * TAU;
  trees.push({ fol, ph: rnd() * TAU });
}
function lamp(x, z, rotY, y = 0){
  const p = prop(x, y, z);
  const g = p.inner; g.rotation.y = rotY;
  boxB(g, 0.28, 0.1, 0.28, C.navy, 0, 0, 0, { r: 0.04 });
  boxB(g, 0.09, 2.3, 0.09, C.navy, 0, 0.05, 0, { r: 0.03 });
  box(g, 0.62, 0.07, 0.07, C.navy, 0.28, 2.32, 0, { r: 0.02 });
  box(g, 0.36, 0.12, 0.22, C.navy, 0.56, 2.26, 0, { r: 0.05 });
  box(g, 0.28, 0.04, 0.16, C.white, 0.56, 2.19, 0, { r: 0.015, emissive: 0xfff1d0, ei: 0.9, cast: false });
}
function bench(x, z, rotY){
  const p = prop(x, 0, z);
  const g = p.inner; g.rotation.y = rotY;
  for (const lx of [-0.4, 0.4]) boxB(g, 0.08, 0.3, 0.34, C.navy, lx, 0, 0, { r: 0.02 });
  boxB(g, 1.1, 0.08, 0.38, C.teal, 0, 0.3, 0, { r: 0.03 });
  boxB(g, 1.1, 0.3, 0.06, C.teal, 0, 0.38, -0.17, { r: 0.03 });
}
function hydrant(x, z, y){
  const p = prop(x, y, z);
  boxB(p.inner, 0.2, 0.36, 0.2, C.royal, 0, 0, 0, { r: 0.07 });
  box(p.inner, 0.32, 0.08, 0.1, C.royal, 0, 0.22, 0, { r: 0.03 });
  boxB(p.inner, 0.24, 0.07, 0.24, C.royalDeep, 0, 0.36, 0, { r: 0.03 });
}
function bin(x, z, y){
  const p = prop(x, y, z);
  boxB(p.inner, 0.3, 0.46, 0.3, C.greenDeep, 0, 0, 0, { r: 0.07 });
  boxB(p.inner, 0.34, 0.06, 0.34, C.navy, 0, 0.46, 0, { r: 0.02 });
}

// outer ring (slab sidewalk between road and edge)
const O = 11.8;
for (const u of [-9.5, -4.5, 1.5, 6.5]){ tree(u, -O); tree(-O, u); }
for (const u of [-8, -2.5]){ tree(u, O, 0, 0.9); tree(O, u, 0, 0.9); }
tree(O, O, 0, 1.1); tree(-O, -O, 0, 1.2); tree(O, -O, 0, 1.05); tree(-O, O, 0, 1.05);
for (const u of [-6.5, 4.0]){ lamp(u, 11.0, Math.PI / 2); lamp(11.0, u, 0); lamp(u, -11.0, -Math.PI / 2); lamp(-11.0, u, Math.PI); }
bench(9.0, 12.2, Math.PI); bench(12.2, 8.5, -Math.PI / 2); bench(-1.5, -12.2, 0);
// inner block sidewalk
lamp(6.0, -1.0, Math.PI, BY); lamp(-1.0, 6.0, -Math.PI / 2, BY); lamp(-6.0, 0.4, 0, BY);
tree(-0.1, 1.7, BY, 0.85); tree(-0.1, 4.4, BY, 0.8); tree(0.3, -5.8, BY, 0.75);
hydrant(6.0, -2.4, BY); bin(0.6, 5.9, BY); bin(6.0, 0.5, BY);

// pedestrians on the outer sidewalk
const walkers = [];
function addWalker(axis, fixed, from, to, shirt, dog){
  const p = prop(0, 0, 0);
  const pr = person(shirt); pr.g.scale.setScalar(0.85); p.inner.add(pr.g);
  let d = null;
  if (dog){
    d = new THREE.Group(); p.inner.add(d);
    box(d, 0.42, 0.2, 0.18, C.white, 0, 0.24, 0, { r: 0.07 });
    box(d, 0.18, 0.18, 0.16, C.white, 0.26, 0.36, 0, { r: 0.06 });
    box(d, 0.06, 0.08, 0.16, C.navy, 0.3, 0.46, 0, { r: 0.02 });
    for (const lx of [-0.14, 0.14]) for (const lz of [-0.06, 0.06]) boxB(d, 0.06, 0.14, 0.06, C.navy, lx, 0, lz, { r: 0.02 });
    box(d, 0.14, 0.04, 0.04, C.white, -0.26, 0.34, 0, { r: 0.015 });
  }
  walkers.push({ p, pr, axis, fixed, from, to, d });
}
addWalker('x', 11.6, -12.4, 12.4, C.royal, true);
addWalker('x', 12.3, 12.4, -12.4, C.green, false);
addWalker('z', 11.7, 12.4, -12.4, C.teal, false);
addWalker('z', 12.35, -12.4, 12.4, C.white, false);

/* ---------- post-processing ---------- */
const rt = new THREE.WebGLRenderTarget(W, H, { type: THREE.HalfFloatType, samples: 4 });
const composer = new EffectComposer(renderer, rt);
composer.setPixelRatio(1);
composer.setSize(W, H);
composer.addPass(new RenderPass(scene, camera));
try {
  const gtao = new GTAOPass(scene, camera, W, H);
  gtao.output = GTAOPass.OUTPUT.Default;
  gtao.blendIntensity = 1.0;
  gtao.updateGtaoMaterial({ radius: 0.3, distanceExponent: 1.4, thickness: 1.2, scale: 1.15, samples: 12, distanceFallOff: 1, screenSpaceRadius: false });
  gtao.updatePdMaterial({ lumaPhi: 10, depthPhi: 2, normalPhi: 3, radius: 6, radiusExponent: 1, rings: 2, samples: 16 });
  composer.addPass(gtao);
} catch (e) { console.warn('GTAO unavailable', e); }
composer.addPass(new OutputPass());

/* ---------- overlay stats ---------- */
const elO = document.getElementById('sOrders'), elR = document.getElementById('sRev'), elD = document.getElementById('sDel'), elDR = document.getElementById('dRev');
const fmtInt = n => n.toLocaleString('en-US');
const dealVal = i => { const x = Math.sin(i * 12.9898) * 43758.5453; return 8000 + (x - Math.floor(x)) * 16000; };
const countSince = (t, first, period) => t < first ? 0 : Math.floor((t - first) / period) + 1;
const REV0 = 184200;
let lastOrders = -1, lastDel = -1, lastDeals = -1, revTarget = REV0, revShown = REV0, revIdx = 0;
function bump(el){ el.classList.remove('bump'); void el.offsetWidth; el.classList.add('bump'); }
function updateStats(t, lt){
  const tasks = 1284 + countSince(t, IN.svc0 + 0.5, IN.step);
  if (tasks !== lastOrders){ elO.textContent = fmtInt(tasks); if (lastOrders >= 0) bump(elO); lastOrders = tasks; }
  const cof = 212 + countSince(t, RUN.refill, RUN.period);
  if (cof !== lastDel){ elD.textContent = fmtInt(cof); if (lastDel >= 0) bump(elD); lastDel = cof; }
  const d = countSince(t, MEET.t0 + MEET.cheer, MEET.period);
  while (revIdx < d){ revTarget += dealVal(revIdx++); }
  if (d !== lastDeals){ if (lastDeals >= 0) bump(elR); lastDeals = d; }
  revShown += (revTarget - revShown) * 0.12;
  if (revTarget - revShown < 1) revShown = revTarget;
  elR.textContent = '$' + fmtInt(Math.round(revShown / 10) * 10);
  elDR.textContent = (12 + d) + ' deals · avg $' + (revShown / (12 + d) / 1000).toFixed(1) + 'k';
}

/* ---------- animation ---------- */
let start = null;
const card = document.querySelector('.card');
function restart(){
  start = null; buildDone = false;
  lastOrders = -1; lastDel = -1; lastDeals = -1; revTarget = REV0; revShown = REV0; revIdx = 0;
  card.style.animation = 'none'; void card.offsetWidth; card.style.animation = '';
}
addEventListener('keydown', e => { if (e.code === 'Space' || e.key === 'r' || e.key === 'R') { e.preventDefault(); restart(); } });
addEventListener('pointerdown', restart);
function frame(now){
  if (start === null) start = now;
  const t = (window.__freezeT ?? (now - start) / 1000), lt = t % LOOP, ph = lt / LOOP;
  applyBuild(t);

  // camera: eased sway-orbit with gentle push in, period = LOOP
  placeCamera(t);
  animateOpen(t);

  // cars: one lap per loop
  for (const v of vehicles){
    const pt = v.path.at(v.offset + ph * v.path.L, v.rev);
    v.p.root.position.set(pt.x, RY, pt.z);
    v.p.root.rotation.y = pt.yaw;
    const spin = -ph * TAU * v.K;
    v.wheels.forEach(w => (w.rotation.z = spin));
  }

  // scooters
  for (const sc of scooters){
    const u = smooth((lt - sc.dep) / sc.dur);
    const pt = bikeLane.at(sc.s0 + u * bikeLane.L, false);
    const lean = Math.sin(u * Math.PI);
    sc.p.root.position.set(pt.x, RY, pt.z);
    sc.p.root.rotation.y = pt.yaw;
    sc.g.position.y = 0.03 * lean * Math.abs(Math.sin(lt * 18));
    sc.wheels.forEach(w => (w.rotation.z = -u * TAU * sc.K));
  }

  // queue: every STEP seconds everyone shuffles forward one slot
  const step = Math.floor(lt / STEP), fr = (lt % STEP) / STEP;
  const move = smooth(fr / 0.5);
  for (const q of queue){
    const u = (q.k + step + move) % QN;
    const i = Math.floor(u), f = u - i;
    const a = QP[i], b = QP[i + 1];
    const x = a[0] + (b[0] - a[0]) * f, z = a[1] + (b[1] - a[1]) * f;
    q.p.root.position.set(x, BY, z);
    const dx = b[0] - a[0], dz = b[1] - a[1];
    if (Math.hypot(dx, dz) > 0.01) q.p.root.rotation.y = Math.atan2(-dz, dx);
    let s = 1;
    if (u < 1) s = smooth(u * 1.4);
    else if (u >= 6) s = 1 - smooth((u - 6) / 0.9);
    q.pr.g.scale.setScalar(Math.max(0.001, 0.85 * s));
    q.pr.g.visible = s > 0.01;
    const moving = fr < 0.5 ? Math.sin(fr / 0.5 * Math.PI) : 0;
    const sw = Math.sin(lt * 14 + q.k) * 0.55 * moving;
    q.pr.legs[0].rotation.z = sw; q.pr.legs[1].rotation.z = -sw;
    q.pr.g.position.y = Math.abs(Math.sin(lt * 14 + q.k)) * 0.04 * moving;
  }

  // walkers along the outer sidewalk
  for (const w of walkers){
    const v = w.from + (w.to - w.from) * ph;
    const dir = Math.sign(w.to - w.from);
    if (w.axis === 'x'){ w.p.root.position.set(v, 0, w.fixed); w.p.root.rotation.y = dir > 0 ? 0 : Math.PI; }
    else { w.p.root.position.set(w.fixed, 0, v); w.p.root.rotation.y = dir > 0 ? -Math.PI / 2 : Math.PI / 2; }
    const edge = Math.min(Math.abs(v - w.from), Math.abs(v - w.to));
    const s = smooth(edge / 0.8);
    w.p.root.scale.setScalar(Math.max(0.001, s));
    const sw = Math.sin(ph * TAU * 14) * 0.55;
    w.pr.legs[0].rotation.z = sw; w.pr.legs[1].rotation.z = -sw;
    w.pr.arms[0].rotation.z = -sw * 0.6; w.pr.arms[1].rotation.z = sw * 0.6;
    w.pr.g.position.y = Math.abs(Math.sin(ph * TAU * 14)) * 0.035;
    if (w.d){ w.d.position.set(0.75, Math.abs(Math.sin(ph * TAU * 28)) * 0.05, 0.35); }
  }

  // ambient motion
  for (const tr of trees){ tr.fol.rotation.z = 0.035 * Math.sin(ph * TAU * 2 + tr.ph); tr.fol.rotation.x = 0.025 * Math.cos(ph * TAU * 2 + tr.ph); }
  fans.forEach((f, i) => (f.rotation.y = ph * TAU * (6 + i)));
  blinkers.forEach(b => (b.material.emissiveIntensity = (lt % 1) < 0.35 ? 2.2 : 0));
  for (const st of steam){
    const u = (ph * 4 + st.phase) % 1;
    st.m.position.set(Math.sin(u * TAU + st.phase * 9) * 0.14, 1.25 + u * 1.7, Math.cos(u * 5 + st.phase * 4) * 0.12);
    st.m.scale.setScalar(0.35 + u * 1.1);
    st.m.material.opacity = 0.85 * Math.sin(u * Math.PI);
    st.m.rotation.y = u * 2;
  }
  for (const sp of sippers){
    const u = (ph * 2 + sp.ph) % 1;
    const lift = smooth(u / 0.2) * (1 - smooth((u - 0.45) / 0.2));
    sp.pr.arms[0].rotation.z = 1.9 * lift;
    sp.pr.g.position.y = 0.06;
  }
  animateShop(lt);

  updateStats(t, lt);
  composer.render();
  requestAnimationFrame(frame);
}
window.__sceneOK = true;
requestAnimationFrame(frame);
</script>
</body>
</html>

Bộ prompt cảnh 3D

Prompt khung có chỗ trống để điền bối cảnh của bạn, prompt quán cà phê, prompt nhà máy AI và chuỗi 8 lệnh nối tiếp (phát lại, sửa lỗi, zoom, cận cảnh, xuyên mái, đổi bối cảnh).

canh-3d-video-doc/prompt/01-prompt-khung-mau.txt
PROMPT KHUNG — DỰNG CẢNH 3D DIORAMA CHO VIDEO DỌC 9:16
Cường Mê AI · Thay các chỗ trong [ngoặc vuông], giữ nguyên phần còn lại.
--------------------------------------------------------------------

Build a single-file web app (HTML, CSS, and JS) that plays a [10]-second looping 3D animation of [CHỦ ĐỀ, ví dụ: a busy street-side bánh mì stall in Saigon], made for a vertical 9:16 video.

Tech: Three.js from a CDN using an import map. RoundedBoxGeometry for every block, MeshStandardMaterial, one sun with soft shadows plus a hemisphere light, ACES tone mapping, and an ambient occlusion pass [GTAO].

World: a floating diorama on a rounded slab, packed with real, recognisable props built from simple shapes: [DANH SÁCH ĐỒ VẬT CỤ THỂ, càng nhiều càng tốt]. Lots of small moving parts.

Motion: the world builds itself in the first second [pieces rise and pop with a little overshoot], then comes alive: [CHUỖI CHUYỂN ĐỘNG CÓ NHÂN QUẢ, ví dụ: customers order, the cook wraps bánh mì, motorbikes stop and leave]. Camera: a slow ease orbit with a gentle push in, looping with no jump.

Style: clean isometric product render. Off-white ground, [3 MÀU CHÍNH] with one bright orange accent. No textures, no 3D text.

Overlay: a frosted-glass card titled "[TÊN THƯƠNG HIỆU - Live Sales]" with three stats that tick up: [CHỈ SỐ 1, CHỈ SỐ 2, CHỈ SỐ 3]. Each stat ticks exactly when its matching action happens in the scene.

Frame: fill a 1088x1920 frame, no scrollbars, autoplay on load. Add Space / R / click to replay from second 0.
canh-3d-video-doc/prompt/02-prompt-quan-ca-phe.txt
PROMPT GỐC — QUÁN CÀ PHÊ GÓC PHỐ "DAILY GRIND"
--------------------------------------------------------------------

Build a single-file web app (HTML, CSS, and JS) that plays a [10]-second looping 3D animation of [a busy corner coffee shop on a city block], made for a vertical 9:16 video.

Tech: Three.js from a CDN using an import map. RoundedBoxGeometry for every block, MeshStandardMaterial, one sun with soft shadows plus a hemisphere light, ACES tone mapping, and an ambient occlusion pass [GTAO].

World: a floating diorama on a rounded slab, packed with real, recognisable props built from simple shapes: [buildings with window grids, trees, cars, delivery scooters, people, street lamps]. Lots of small moving parts.

Motion: the world builds itself in the first second [pieces rise and pop with a little overshoot], then comes alive: [customers queue, scooters drive off, cars loop the block]. Camera: a slow ease orbit with a gentle push in, looping with no jump.

Style: clean isometric product render. Off-white ground, [royal blue, teal and green] with one bright orange accent. No textures, no 3D text.

Overlay: a frosted-glass card titled "[Daily Grind - Live Sales]" with three stats that tick up.

Frame: fill a 1088x1920 frame, no scrollbars, autoplay on load.
canh-3d-video-doc/prompt/03-prompt-nha-may-ai.txt
PROMPT — NHÀ MÁY AI "NEUROFORGE"
--------------------------------------------------------------------

Build a single-file web app (HTML, CSS, and JS) that plays a [10]-second looping 3D animation of [a futuristic AI factory campus], made for a vertical 9:16 video.

Tech: Three.js from a CDN using an import map. RoundedBoxGeometry for every block, MeshStandardMaterial, one sun with soft shadows plus a hemisphere light, ACES tone mapping, and an ambient occlusion pass [GTAO].

World: a floating diorama on a rounded slab, packed with real, recognisable props built from simple shapes: [a main factory hall with a glass roof, rows of GPU server racks with blinking status lights, robotic arms, conveyor belts carrying glowing chips, cooling towers with fans, solar panel arrays, autonomous delivery trucks, drones, engineers in hard hats]. Lots of small moving parts.

Motion: the world builds itself in the first second [pieces rise and pop with a little overshoot], then comes alive: [robotic arms pick and place chips onto the conveyor, chips travel into the server hall and light up the racks, cooling fans spin, drones lift off from rooftop pads with packages, trucks loop the campus road, engineers walk between buildings]. Camera: a slow ease orbit with a gentle push in, looping with no jump.

Style: clean isometric product render. Off-white ground, [royal blue, teal and green] with one bright orange accent. No textures, no 3D text.

Overlay: a frosted-glass card titled "[NeuroForge - Live Output]" with three stats that tick up: [Tokens generated, GPUs online, Models shipped].

Frame: fill a 1088x1920 frame, no scrollbars, autoplay on load.
canh-3d-video-doc/prompt/04-chuoi-lenh-noi-tiep.txt
CHUỖI LỆNH NỐI TIẾP — Dán từng câu vào Claude sau khi đã có cảnh đầu tiên
--------------------------------------------------------------------

[1] Thêm nút phát lại để quay đoạn mở màn
Thêm phím Space, phím R và click chuột để phát lại cảnh từ giây 0: dựng lại thế giới, chạy lại hiệu ứng thẻ, đưa số liệu về giá trị ban đầu.

[2] Khi trang trắng, không load được
Trang không load được. Đổi cách tải Three.js sang đường dẫn đầy đủ, không phụ thuộc import map. Giảm shadow map xuống 2048 và số mẫu GTAO xuống 12. Nếu cảnh không chạy được thì hiện một dòng báo lỗi ở cuối trang.

[3] Zoom gần hơn
Zoom camera vào gần khoảng gấp đôi, lấy quán cà phê làm tâm khung. Giữ chuyển động xoay chậm và đẩy vào nhẹ, lặp 10 giây không giật.

[4] Cận cảnh bên trong
Làm thêm một bản riêng: zoom hẳn vào bên trong quán để thấy barista và quầy pha chế. Cắt bỏ mái và hai bức tường phía trước như nhà búp bê. Mỗi 2,5 giây phục vụ xong một khách: gọi món, pha espresso, giao ly. Số Orders nhảy đúng lúc khách gọi món.

[5] Cảnh mở đầu: một cú máy xuyên mái
Làm cảnh mở đầu 12 giây, một cú máy liền mạch, không lặp: 0–4s toàn cảnh khu phố tự dựng lên; 4–6s camera lao xuống nóc quán; 6–7s mặt kính chìm xuống, tầng trên bật tung và bay vụt qua camera; 7–9s rơi vào trong và dừng ở cận cảnh barista đang pha cà phê. Sau đó camera đung đưa nhẹ để khung hình vẫn sống.

[6] Đổi bối cảnh sang văn phòng
Làm một bản tương tự nhưng là văn phòng: tòa nhà kính nhiều tầng, bên trong có cụm bàn làm việc, nhóm họp đứng ở bảng trắng, màn hình biểu đồ trên tường, góc pha cà phê. Thẻ số liệu gồm Tasks done, Closed today, Coffees, nhảy theo hành động trong cảnh.

[7] Sửa lỗi hay gặp
- Phía trước bị cắt mất khi zoom gần, chỉnh near plane của camera nhỏ lại.
- Cảnh chạy giật: giảm shadow map xuống 1024 và tắt GTAO.
- Có vật che góc nhìn: bỏ hoặc dời [tên vật].

[8] Cá nhân hóa
Đổi tên thẻ thành [tên của bạn], chuyển chữ trên thẻ sang tiếng Việt, đổi màu nhấn sang [màu].

Mô hình nhà máy nước tương tác

Dây chuyền chiết rót nước 1,5L: 60 van chiết, 18 đầu đóng nắp, soi đèn loại lỗi, dán nhãn, màng co, robot xếp pallet, kho; đầy đủ tương tác và tour 9 chương. Nhấn T để chạy tour.

nha-may-nuoc/nha-may-nuoc.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
</head>
<body>
<title>Nhà Máy Nước 1.5L</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Be+Vietnam+Pro:wght@400;500;600;700;800&family=JetBrains+Mono:wght@500;700&display=swap">
<style>
/* Layout: full-window 3D canvas; HUD = top bar, KPI cards top-left, device panel top-right, caption + minimap bottom-left, control bar bottom-center. Single light "control room" look, set explicitly. */
:root{
  --bg:#e6eaef;
  --card:rgba(255,255,255,.94);
  --ink:#151a22;
  --muted:#6a7381;
  --line:#e3e7ec;
  --blue:#2563eb;
  --accent:#ff6a1a;
  --ok:#16a34a;
  --warn:#d97706;
  --bad:#e11d48;
  --cap:rgba(22,24,29,.9);
  --f-ui:'Be Vietnam Pro',system-ui,-apple-system,'Segoe UI',sans-serif;
  --f-num:'JetBrains Mono',ui-monospace,Menlo,Consolas,monospace;
  color-scheme:light;
}
html,body{height:100%;margin:0;overflow:hidden;background:var(--bg);color:var(--ink);font-family:var(--f-ui)}
#c{position:fixed;inset:0;width:100%;height:100%;display:block;outline:none;touch-action:none}
#labels{position:fixed;inset:0;pointer-events:none;overflow:hidden}
.tag{position:absolute;transform:translate(-50%,-100%);pointer-events:auto;cursor:pointer;white-space:nowrap;
  font-size:12px;font-weight:600;color:#fff;background:rgba(28,31,37,.86);padding:4px 9px;border-radius:7px;
  box-shadow:0 4px 12px rgba(0,0,0,.18);transition:opacity .2s}
.tag::after{content:"";position:absolute;left:50%;bottom:-4px;transform:translateX(-50%);border:4px solid transparent;border-top-color:rgba(28,31,37,.86);border-bottom:0}
.tag.sel{background:var(--blue)}
.tag.sel::after{border-top-color:var(--blue)}
.tag.part{background:#fff;color:var(--ink);border:1px solid var(--line)}
.tag.part::after{border-top-color:#fff}
.tag.ng{background:var(--bad)}
.tag.ng::after{border-top-color:var(--bad)}

.top{position:fixed;left:0;right:0;top:0;height:46px;display:flex;align-items:center;gap:18px;
  padding:0 max(16px,env(safe-area-inset-right,0px)) 0 max(16px,env(safe-area-inset-left,0px));
  background:rgba(255,255,255,.92);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);border-bottom:1px solid var(--line);z-index:5}
.brand{display:flex;align-items:center;gap:10px;flex:none}
.logo{width:28px;height:28px;border-radius:8px;background:var(--blue);display:grid;place-items:center}
.logo svg{width:18px;height:18px}
.brand b{font-size:15px;font-weight:800;letter-spacing:-.01em;display:block;line-height:1.1}
.brand span{font-size:11px;color:var(--muted);font-weight:500}
.tabs{display:flex;gap:2px;min-width:0;overflow-x:auto;scrollbar-width:none}
.tabs::-webkit-scrollbar{display:none}
.tabs button{font:600 13px var(--f-ui);color:#3d4652;background:none;border:0;padding:7px 10px;border-radius:8px;cursor:pointer;white-space:nowrap}
.tabs button:hover{background:#eef2f7}
.tabs button.on{color:var(--blue);background:#e8efff}
.status{margin-left:auto;display:flex;align-items:center;gap:14px;flex:none}
.pill{display:flex;align-items:center;gap:7px;font-size:13px;font-weight:700;color:var(--ok)}
.pill i{width:9px;height:9px;border-radius:50%;background:currentColor;box-shadow:0 0 0 3px color-mix(in srgb,currentColor 20%,transparent)}
.pill.warn{color:var(--warn)} .pill.bad{color:var(--bad)}
.clock{text-align:right;line-height:1.05}
.clock small{display:block;font-size:10px;color:var(--muted);font-weight:500}
.clock b{font:700 15px var(--f-num)}

.card{background:var(--card);border:1px solid rgba(255,255,255,.7);border-radius:12px;box-shadow:0 8px 24px -8px rgba(20,30,50,.22)}
.kpis{position:fixed;left:max(14px,env(safe-area-inset-left,0px));top:58px;display:flex;flex-direction:column;gap:8px;z-index:4}
.kpi{padding:9px 14px 10px;min-width:150px}
.k-lab{display:flex;align-items:center;gap:6px;font-size:11.5px;font-weight:600;color:var(--muted)}
.k-lab svg{width:13px;height:13px}
.k-big{font:700 24px/1.1 var(--f-num);color:var(--blue);margin-top:2px;font-variant-numeric:tabular-nums}
.k-mid{font:700 22px/1.1 var(--f-num);margin-top:2px;font-variant-numeric:tabular-nums}
.k-mid small{font:500 11px var(--f-ui);color:var(--muted);margin-left:3px}
.k-row2{display:flex;gap:16px;margin-top:2px}
.k-row2 b{font:700 15px var(--f-num);font-variant-numeric:tabular-nums}
.k-row2 .bad{color:var(--bad)}
.badge{position:fixed;left:190px;top:58px;z-index:4;background:rgba(22,24,29,.88);color:#fff;font-weight:700;font-size:17px;padding:8px 14px;border-radius:8px;letter-spacing:-.01em}
.badge em{font-style:normal;color:#ff8a3d}

.panel{position:fixed;right:max(14px,env(safe-area-inset-right,0px));top:58px;width:250px;padding:12px 14px;z-index:4;max-height:calc(100% - 150px);overflow:auto}
.p-eye{font-size:11px;font-weight:600;color:var(--muted)}
.p-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin:2px 0 8px}
.p-title{font-size:17px;font-weight:800;letter-spacing:-.01em;line-height:1.2}
.chip{flex:none;font-size:11px;font-weight:700;padding:3px 8px;border-radius:99px;background:#dcfce7;color:#15803d}
.chip.warn{background:#fef3c7;color:#b45309}.chip.bad{background:#ffe4e6;color:#be123c}.chip.idle{background:#eef2f7;color:#475569}
.rows{display:flex;flex-direction:column}
.row{display:flex;justify-content:space-between;gap:10px;padding:6px 0;border-top:1px solid var(--line);font-size:13px}
.row span{color:#4b5563}
.row b{font:700 12.5px var(--f-num);text-align:right;font-variant-numeric:tabular-nums}
.row b.blue{color:var(--blue)} .row b.bad{color:var(--bad)} .row b.warn{color:var(--warn)}
.tl{margin-top:8px;border-top:1px solid var(--line);padding-top:6px}
.tl div{display:flex;align-items:center;gap:8px;font-size:12.5px;padding:4px 0;color:#9aa3af}
.tl i{width:11px;height:11px;border-radius:50%;border:2px solid #cbd2db;flex:none;box-sizing:border-box}
.tl div.done{color:var(--ink)} .tl div.done i{background:var(--blue);border-color:var(--blue)}
.tl div.cur{color:var(--blue);font-weight:700} .tl div.cur i{border-color:var(--blue);box-shadow:0 0 0 3px #dbe6ff}
.tl div.ng{color:var(--bad);font-weight:700} .tl div.ng i{background:var(--bad);border-color:var(--bad)}
.tl time{margin-left:auto;font:600 11.5px var(--f-num)}
.p-hint{font-size:12px;color:var(--muted);margin-top:8px;line-height:1.45}

.caption{position:fixed;left:50%;bottom:76px;transform:translateX(-50%);width:min(760px,calc(100% - 420px));min-width:min(520px,calc(100% - 32px));
  background:var(--cap);color:#fff;border-radius:12px;border-left:4px solid var(--accent);padding:16px 24px 18px;z-index:4;box-sizing:border-box;transition:opacity .35s}
.cap-eye{display:flex;gap:14px;font-size:12px;font-weight:600;letter-spacing:.12em;color:#9aa1ab}
.cap-eye b{color:var(--accent);font-family:var(--f-num);letter-spacing:.04em}
.cap-title{font-size:30px;font-weight:800;letter-spacing:-.02em;margin-top:4px;line-height:1.2;text-wrap:balance}
.cap-sub{font-size:16px;color:#cfd4db;margin-top:4px;line-height:1.45}
.cap-bar{position:absolute;left:0;right:0;bottom:0;height:3px;border-radius:0 0 12px 0;overflow:hidden}
.cap-bar i{display:block;height:100%;width:0;background:var(--accent)}

.mini{position:fixed;left:max(14px,env(safe-area-inset-left,0px));bottom:14px;width:220px;height:130px;padding:6px;z-index:4;cursor:crosshair}
.mini canvas{width:100%;height:100%;display:block;border-radius:8px}

.bar{position:fixed;left:250px;right:max(14px,env(safe-area-inset-right,0px));bottom:14px;margin:0 auto;width:fit-content;display:flex;align-items:center;gap:4px;padding:5px;z-index:5;max-width:calc(100% - 264px);overflow-x:auto;scrollbar-width:none;box-sizing:border-box}
.bar::-webkit-scrollbar{display:none}
.bar .sep{width:1px;height:22px;background:var(--line);margin:0 2px;flex:none}
.b{font:600 12.5px var(--f-ui);color:#2a313b;background:#fff;border:1px solid transparent;padding:7px 9px;border-radius:8px;cursor:pointer;white-space:nowrap;display:inline-flex;align-items:center;gap:6px;flex:none}
.b:hover{background:#f1f4f8}
.b svg{width:14px;height:14px}
.b.on{background:var(--blue);color:#fff}
.b.ic{padding:7px 9px}
.b.amber{background:#fff7ed;border-color:#fed7aa;color:#9a3412}
.b.amber.on{background:var(--warn);border-color:var(--warn);color:#fff}
.b.red{background:var(--bad);color:#fff}
.b.red.on{background:#7f1d1d}
.b.tour{background:var(--ink);color:#fff}
.b.tour.on{background:var(--accent)}
.b:focus-visible,.tabs button:focus-visible{outline:2px solid var(--blue);outline-offset:2px}
.slider{display:flex;align-items:center;gap:6px;font:600 12.5px var(--f-ui);color:#2a313b;padding:0 4px;flex:none}
.slider input{width:64px;accent-color:var(--blue)}

.toast{position:fixed;left:50%;top:60px;transform:translate(-50%,-20px);opacity:0;z-index:6;padding:9px 16px;border-radius:10px;font-weight:700;font-size:14px;color:#fff;background:var(--ink);
  box-shadow:0 10px 30px -8px rgba(0,0,0,.35);transition:opacity .25s,transform .25s;pointer-events:none;white-space:nowrap}
.toast.show{opacity:1;transform:translate(-50%,0)}
.toast.bad{background:var(--bad)}.toast.warn{background:var(--warn)}.toast.ok{background:var(--ok)}
#err{position:fixed;left:16px;right:16px;bottom:16px;padding:12px 14px;border-radius:10px;background:#151a22;color:#fff;font-size:14px;z-index:9}

@media (max-width:900px){
  .badge,.panel{display:none}
  .caption{width:calc(100% - 32px);min-width:0;bottom:70px}
  .cap-title{font-size:22px}.cap-sub{font-size:14px}
  .mini{display:none}
  .bar{left:12px;right:12px;max-width:calc(100% - 24px)}
}
@media (max-aspect-ratio:3/4){ .caption{bottom:120px} }
@media (prefers-reduced-motion:reduce){ .toast,.caption{transition:none} }
</style>

<canvas id="c" tabindex="0" aria-label="Mô hình 3D nhà máy nước"></canvas>
<div id="labels"></div>

<header class="top">
  <div class="brand">
    <div class="logo"><svg viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3c3 4 6 7 6 11a6 6 0 0 1-12 0c0-4 3-7 6-11Z"/></svg></div>
    <div><b>Nhà máy nước</b><span>Bản sao số dây chuyền 1.5L</span></div>
  </div>
  <nav class="tabs" id="tabs" aria-label="Khu vực"></nav>
  <div class="status">
    <span class="pill" id="pill"><i></i><span id="pillTxt">Đang chạy</span></span>
    <div class="clock"><small>Giờ sản xuất</small><b id="clock">08:40:00</b></div>
  </div>
</header>

<div class="kpis">
  <div class="kpi card">
    <div class="k-lab"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 16a8 8 0 1 1 16 0"/><path d="M12 16l4-5"/></svg>OEE · 10 phút gần nhất</div>
    <div class="k-big" id="kOee">89,2%</div>
  </div>
  <div class="kpi card">
    <div class="k-lab"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 17l6-6 4 4 8-8"/><path d="M15 7h6v6"/></svg>Sản lượng thực</div>
    <div class="k-mid"><span id="kRate">24.000</span><small>chai/giờ</small></div>
    <div class="k-row2"><div><div class="k-lab">Hôm nay</div><b id="kToday">186.420</b></div><div><div class="k-lab">Đã loại</div><b class="bad" id="kRej">37</b></div></div>
  </div>
</div>
<div class="badge">Claude Code × <em>Three.js</em></div>

<aside class="panel card" id="panel" aria-live="polite"></aside>

<div class="caption" id="caption">
  <div class="cap-eye"><b id="capNum">TƯƠNG TÁC</b><span id="capEye">LIVE INTERACTION</span></div>
  <div class="cap-title" id="capTitle">Nhà máy này là một trang web.</div>
  <div class="cap-sub" id="capSub">Bấm vào máy hoặc một chai nước · kéo để xoay · cuộn để phóng to</div>
  <div class="cap-bar"><i id="capBar"></i></div>
</div>

<div class="mini card" id="miniWrap" title="Bấm để di chuyển tới vị trí"><canvas id="mini" width="416" height="236"></canvas></div>

<div class="bar card" role="toolbar" aria-label="Điều khiển">
  <button class="b tour" id="bTour"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M7 4.5v15l12-7.5z"/></svg><span>Chạy tour</span></button>
  <span class="sep"></span>
  <button class="b ic" id="bPause" aria-label="Tạm dừng mô phỏng"><svg viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="5" width="4" height="14" rx="1"/><rect x="14" y="5" width="4" height="14" rx="1"/></svg></button>
  <button class="b on" data-rate="1">1×</button>
  <button class="b" data-rate="2">2×</button>
  <button class="b" data-rate="4">4×</button>
  <span class="sep"></span>
  <button class="b" id="bFollow">Truy vết chai</button>
  <button class="b" id="bXray">Xuyên thấu</button>
  <label class="slider" for="explode">Tách lớp <input id="explode" type="range" min="0" max="1" step="0.01" value="0"></label>
  <span class="sep"></span>
  <button class="b amber" id="bDefect">Gây thiếu nắp</button>
  <button class="b amber" id="bAlarm">Lỗi van chiết</button>
  <button class="b red" id="bStop">Dừng khẩn</button>
  <button class="b" id="bReset">Đặt lại</button>
</div>

<div class="toast" id="toast" role="status"></div>
<div id="err" hidden></div>
<script>
(function(){
  var el=document.getElementById('err');
  function show(m){ el.hidden=false; el.textContent='Không chạy được cảnh 3D: '+m; }
  window.addEventListener('error',function(e){ show(e.message||'lỗi tải script'); },true);
  window.addEventListener('unhandledrejection',function(e){ show(String(e.reason&&e.reason.message||e.reason)); });
  setTimeout(function(){ if(!window.__sceneOK) show('thư viện Three.js chưa tải xong sau 20 giây (mạng hoặc CDN bị chặn).'); },20000);
})();
</script>

<script type="module">
import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.160.0/+esm';
import { OrbitControls } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/controls/OrbitControls.js/+esm';
import { RoundedBoxGeometry } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/geometries/RoundedBoxGeometry.js/+esm';
import { EffectComposer } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/EffectComposer.js/+esm';
import { RenderPass } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/RenderPass.js/+esm';
import { GTAOPass } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/GTAOPass.js/+esm';
import { OutputPass } from 'https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/postprocessing/OutputPass.js/+esm';

const TAU = Math.PI * 2;
const clamp01 = x => Math.min(1, Math.max(0, x));
const smooth = x => { x = clamp01(x); return x * x * (3 - 2 * x); };
const easeIO = x => { x = clamp01(x); return x < .5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2; };
const lerp = (a, b, t) => a + (b - a) * t;
const mod = (a, n) => ((a % n) + n) % n;
const NF = new Intl.NumberFormat('vi-VN');
const fmt = n => NF.format(n);
const fmt1 = n => n.toLocaleString('vi-VN', { minimumFractionDigits: 1, maximumFractionDigits: 1 });
const fmt2 = n => n.toLocaleString('vi-VN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

/* ================= renderer / scene ================= */
const canvas = document.getElementById('c');
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: 'high-performance' });
const DPR = Math.min(window.devicePixelRatio || 1, 1.5);
renderer.setPixelRatio(DPR);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.02;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;

const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe4e8ed);
const camera = new THREE.PerspectiveCamera(36, innerWidth / innerHeight, 0.08, 260);
const controls = new OrbitControls(camera, canvas);
controls.enableDamping = true; controls.dampingFactor = 0.08;
controls.maxPolarAngle = 1.48; controls.minDistance = 0.8; controls.maxDistance = 75;
controls.autoRotateSpeed = 0.35;

scene.add(new THREE.HemisphereLight(0xf4f7ff, 0xb8b2a6, 1.25));
const sun = new THREE.DirectionalLight(0xfff4e4, 2.3);
sun.position.set(-12, 30, 18); sun.castShadow = true;
sun.shadow.mapSize.set(4096, 4096);
Object.assign(sun.shadow.camera, { left: -26, right: 26, top: 22, bottom: -22, near: 1, far: 90 });
sun.shadow.bias = -0.0004; sun.shadow.normalBias = 0.03; sun.shadow.radius = 4;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xdfe8ff, 0.45); fill.position.set(20, 12, -10); scene.add(fill);

/* ================= helpers ================= */
const C = {
  floor: 0xd3d7dd, wall: 0xeceef1, wallBand: 0x8ea1b6, steel: 0xb9c0c8, steelDark: 0x5c646f, frame: 0x353a42,
  white: 0xf3f4f6, machine: 0xe8ebee, orange: 0xff6a1a, yellow: 0xf2c21b, green: 0x46b06f, blue: 0x2f6fdf,
  cap: 0x1d5ed6, glass: 0xcfe6f2, chain: 0x41464e, wood: 0xc9a574, film: 0xdde9f2, suit: 0x2f5fa8, skin: 0xe2b48f, red: 0xd8343b
};
const gCache = new Map(), mCache = new Map();
function rgeo(w, h, d, r){ r = Math.min(r, Math.min(w, h, d) / 2 - 0.0005); const k = `r${w.toFixed(3)}|${h.toFixed(3)}|${d.toFixed(3)}|${r.toFixed(4)}`; if (!gCache.has(k)) gCache.set(k, new RoundedBoxGeometry(w, h, d, 2, Math.max(0.0005, r))); return gCache.get(k); }
function cgeo(rt, rb, h, seg = 24, open = false){ const k = `c${rt}|${rb}|${h}|${seg}|${open}`; if (!gCache.has(k)) gCache.set(k, new THREE.CylinderGeometry(rt, rb, h, seg, 1, open)); return gCache.get(k); }
function M(color, o = {}){
  const k = [color, o.rough, o.metal, o.em, o.ei, o.op].join('|');
  if (o.unique || !mCache.has(k)){
    const m = new THREE.MeshStandardMaterial({ color, roughness: o.rough ?? 0.6, metalness: o.metal ?? 0, emissive: o.em ?? 0x000000, emissiveIntensity: o.ei ?? 1,
      transparent: o.op !== undefined, opacity: o.op ?? 1, depthWrite: o.op === undefined });
    if (o.unique) return m;
    mCache.set(k, m);
  }
  return mCache.get(k);
}
const steelM = M(C.steel, { metal: 0.55, rough: 0.35 });
const darkM = M(C.steelDark, { metal: 0.3, rough: 0.5 });
const frameM = M(C.frame, { metal: 0.3, rough: 0.5 });
function mesh(parent, geo, mat, x, y, z, o = {}){
  const m = new THREE.Mesh(geo, mat); m.position.set(x, y, z);
  m.castShadow = o.cast !== false; m.receiveShadow = true; parent.add(m); return m;
}
// bottom-aligned rounded box
function B(parent, w, h, d, color, x = 0, y = 0, z = 0, o = {}){
  const r = o.r ?? Math.min(0.03, Math.min(w, h, d) * 0.2);
  return mesh(parent, rgeo(w, h, d, r), o.mat || M(color, o), x, y + h / 2, z, o);
}
// bottom-aligned cylinder
function CY(parent, r, h, color, x = 0, y = 0, z = 0, o = {}){
  return mesh(parent, cgeo(o.rt ?? r, r, h, o.seg ?? 24, o.open), o.mat || M(color, o), x, y + h / 2, z, o);
}
const _up = new THREE.Vector3(0, 1, 0);
function pipe(parent, a, b, r, mat, o = {}){
  const d = new THREE.Vector3().subVectors(b, a), len = d.length();
  const m = mesh(parent, cgeo(r, r, len, o.seg ?? 14), mat, (a.x + b.x) / 2, (a.y + b.y) / 2, (a.z + b.z) / 2, o);
  m.quaternion.setFromUnitVectors(_up, d.normalize()); return m;
}
function V(x, y, z){ return new THREE.Vector3(x, y, z); }
function group(parent, x = 0, y = 0, z = 0){ const g = new THREE.Group(); g.position.set(x, y, z); parent.add(g); return g; }

/* ================= line path (turtle) ================= */
class Path {
  constructor(){ this.segs = []; this.L = 0; }
  start(x, z, h){ this.x = x; this.z = z; this.h = h; }
  line(len){ const s = { t: 'L', s0: this.L, len, x0: this.x, z0: this.z, h: this.h }; this.segs.push(s); this.x += Math.cos(this.h) * len; this.z += Math.sin(this.h) * len; this.L += len; return s; }
  arc(R, ang){
    const sg = Math.sign(ang), s = { t: 'A', s0: this.L, len: R * Math.abs(ang), R, sg, h0: this.h,
      cx: this.x + sg * R * -Math.sin(this.h), cz: this.z + sg * R * Math.cos(this.h) };
    this.segs.push(s); this.h += ang;
    this.x = s.cx + sg * R * Math.sin(this.h); this.z = s.cz - sg * R * Math.cos(this.h); this.L += s.len; return s;
  }
  on(g, l, o){ if (g.t === 'L'){ o.x = g.x0 + Math.cos(g.h) * l; o.z = g.z0 + Math.sin(g.h) * l; }
    else { const h = g.h0 + g.sg * l / g.R; o.x = g.cx + g.sg * g.R * Math.sin(h); o.z = g.cz - g.sg * g.R * Math.cos(h); } return o; }
  at(s, o){ let g = this.segs[this.segs.length - 1]; for (const q of this.segs) if (s < q.s0 + q.len){ g = q; break; } return this.on(g, s - g.s0, o); }
}
const P = 0.125, LINE_Y = 0.9, NV = 60, NCAP = 18;
const RF = NV * P / TAU, RC = NCAP * P / TAU;
const path = new Path();
path.start(-13.5, 0, 0);
path.line(4.5);
const segF = path.arc(RF, Math.PI);
const segC = path.arc(RC, -Math.PI);
const segOut = path.line(12.0);
const LPATH = path.L, ZL = segOut.z0;                      // out line z
const S_FILL0 = segF.s0 + 0.12 * segF.len, S_FILL1 = segF.s0 + 0.86 * segF.len;
const S_CAP = segC.s0 + 0.55 * segC.len;
const S_INSP = segOut.s0 + 3.5, S_REJ = S_INSP + 0.7, S_LABEL = segOut.s0 + 7.6, S_END = LPATH;
const X_INSP = segOut.x0 + 3.5, X_REJ = X_INSP + 0.7, X_LABEL = segOut.x0 + 7.6, X_END = segOut.x0 + 12;
const PACK_X0 = X_END + 1.6, LP = 7.8, PACK_P = 0.6, PACK_Y = 0.78;   // pack conveyor
const STATIONS = [
  { k: 'blow', name: 'Thổi chai', s: 0 }, { k: 'air', name: 'Băng tải gió', s: 1.2 }, { k: 'fill', name: 'Chiết rót', s: S_FILL0 },
  { k: 'cap', name: 'Đóng nắp', s: S_CAP }, { k: 'insp', name: 'Soi đèn', s: S_INSP }, { k: 'label', name: 'Dán nhãn', s: S_LABEL },
  { k: 'wrap', name: 'Màng co thành lốc', s: S_END }
];

/* ================= hall ================= */
const HALL = { x0: -22, x1: 21, z0: -9.5, z1: 9.5, h: 7.5 };
{
  const fl = new THREE.Mesh(new THREE.PlaneGeometry(HALL.x1 - HALL.x0 + 14, HALL.z1 - HALL.z0 + 14), M(C.floor, { rough: 0.85 }));
  fl.rotation.x = -Math.PI / 2; fl.position.set((HALL.x0 + HALL.x1) / 2, 0, (HALL.z0 + HALL.z1) / 2 + 3); fl.receiveShadow = true; scene.add(fl);
  // green walkway + yellow zone lines
  const gm = M(C.green, { rough: 0.7 }), ym = M(C.yellow, { rough: 0.6 });
  B(scene, HALL.x1 - HALL.x0, 0.012, 1.7, 0, (HALL.x0 + HALL.x1) / 2, 0.001, 7.4, { mat: gm, cast: false, r: 0.004 });
  const zone = (x0, z0, x1, z1) => {
    B(scene, x1 - x0, 0.012, 0.08, 0, (x0 + x1) / 2, 0.002, z0, { mat: ym, cast: false, r: 0.004 });
    B(scene, x1 - x0, 0.012, 0.08, 0, (x0 + x1) / 2, 0.002, z1, { mat: ym, cast: false, r: 0.004 });
    B(scene, 0.08, 0.012, z1 - z0, 0, x0, 0.002, (z0 + z1) / 2, { mat: ym, cast: false, r: 0.004 });
    B(scene, 0.08, 0.012, z1 - z0, 0, x1, 0.002, (z0 + z1) / 2, { mat: ym, cast: false, r: 0.004 });
  };
  zone(-18.6, -2.0, -12.6, 2.0); zone(-11.6, -0.9, -6.4, 4.5); zone(-6.2, 1.9, 2.6, 4.5); zone(2.8, 1.9, 9.2, 4.6); zone(10.9, -0.8, 15.6, 4.6);
  // walls
  const wm = M(C.wall, { rough: 0.9 }), bm = M(C.wallBand, { rough: 0.8 });
  B(scene, HALL.x1 - HALL.x0, HALL.h, 0.3, 0, (HALL.x0 + HALL.x1) / 2, 0, HALL.z0, { mat: wm });
  B(scene, 0.3, HALL.h, HALL.z1 - HALL.z0, 0, HALL.x0, 0, 0, { mat: wm });
  B(scene, HALL.x1 - HALL.x0, 1.2, 0.34, 0, (HALL.x0 + HALL.x1) / 2, 0, HALL.z0, { mat: bm });
  B(scene, 0.34, 1.2, HALL.z1 - HALL.z0, 0, HALL.x0, 0, 0, { mat: bm });
  const winM = M(0xbcd3e6, { rough: 0.2, metal: 0.2 });
  for (let x = HALL.x0 + 2; x < HALL.x1 - 2; x += 3.2) B(scene, 2.6, 1.1, 0.06, 0, x + 1.3, 5.2, HALL.z0 + 0.18, { mat: winM, cast: false });
  for (let z = HALL.z0 + 1.5; z < HALL.z1 - 2; z += 3.2) B(scene, 0.06, 1.1, 2.6, 0, HALL.x0 + 0.18, 5.2, z + 1.3, { mat: winM, cast: false });
  // columns
  for (let x = HALL.x0 + 6; x < HALL.x1; x += 6) B(scene, 0.42, HALL.h, 0.42, 0, x, 0, HALL.z0 + 0.4, { mat: frameM });
  for (let z = HALL.z0 + 6; z < HALL.z1; z += 6) B(scene, 0.42, HALL.h, 0.42, 0, HALL.x0 + 0.4, 0, z, { mat: frameM });
  // long overhead pipe rack
  const pm = M(0xb4532a, { rough: 0.5, metal: 0.2 });
  pipe(scene, V(HALL.x0 + 0.5, 5.6, -7.6), V(HALL.x1 - 1, 5.6, -7.6), 0.13, pm);
  pipe(scene, V(HALL.x0 + 0.5, 5.25, -7.9), V(HALL.x1 - 1, 5.25, -7.9), 0.09, M(0x6f8fb0, { rough: 0.4, metal: 0.4 }));
  for (let x = HALL.x0 + 3; x < HALL.x1; x += 6) B(scene, 0.12, 5.7, 0.12, 0, x, 0, -7.2, { mat: frameM });
  // electrical cabinets
  for (let i = 0; i < 7; i++){
    const x = -6.2 + i * 0.72;
    B(scene, 0.68, 2.0, 0.55, 0xe3e6ea, x, 0, -8.95, { rough: 0.5 });
    B(scene, 0.06, 0.06, 0.02, 0, x + 0.2, 1.65, -8.66, { mat: M(i % 3 ? 0x22c55e : 0x3b82f6, { em: i % 3 ? 0x22c55e : 0x3b82f6, ei: 1.2 }), cast: false });
  }
  // yellow bollards
  const yb = M(C.yellow, { rough: 0.5 });
  for (const [x, z] of [[-12.2, 4.9], [-6.0, 4.9], [2.7, 4.9], [9.6, 4.9], [16.2, 4.9]]) CY(scene, 0.07, 0.9, 0, x, 0, z, { mat: yb, seg: 14 });
}

/* ================= machine registry ================= */
const MACH = {};
const pickRoots = [];
function machine(id, def){ MACH[id] = def; if (def.root){ def.root.traverse(o => { o.userData.mid = id; }); pickRoots.push(def.root); } return def; }
// a "cabin": white roof slab on dark posts, glass sides, white base with orange stripe
const glassM = M(0xd6eaf4, { rough: 0.08, metal: 0.1, op: 0.22 });
const housingMats = [];
function cabin(parent, w, d, h, o = {}){
  const g = group(parent);
  B(g, w, 0.32, d, C.white, 0, 0, 0, { r: 0.03 });
  B(g, w + 0.02, 0.07, d + 0.02, C.orange, 0, 0.2, 0, { r: 0.02 });
  for (const sx of [-1, 1]) for (const sz of [-1, 1]) B(g, 0.08, h - 0.32, 0.08, 0, sx * (w / 2 - 0.04), 0.32, sz * (d / 2 - 0.04), { mat: frameM });
  if (!o.noGlass){
    const gm = o.glassMat || glassM;
    B(g, w - 0.1, h - 0.5, 0.02, 0, 0, 0.36, d / 2 - 0.04, { mat: gm, cast: false });
    B(g, w - 0.1, h - 0.5, 0.02, 0, 0, 0.36, -d / 2 + 0.04, { mat: gm, cast: false });
    B(g, 0.02, h - 0.5, d - 0.1, 0, w / 2 - 0.04, 0.36, 0, { mat: gm, cast: false });
    B(g, 0.02, h - 0.5, d - 0.1, 0, -w / 2 + 0.04, 0.36, 0, { mat: gm, cast: false });
  }
  const roofM = M(C.white, { rough: 0.55, unique: true }); housingMats.push(roofM);
  B(g, w + 0.18, 0.14, d + 0.18, 0, 0, h, 0, { mat: roofM, r: 0.04 });
  return g;
}
const conveyorLegs = (parent, x0, x1, z, top, w = 0.18) => {
  const len = x1 - x0, cx = (x0 + x1) / 2;
  B(parent, len, 0.05, w - 0.04, 0, cx, top - 0.05, z, { mat: M(C.chain, { rough: 0.5, metal: 0.2 }), r: 0.01 });
  for (const sz of [-1, 1]) B(parent, len, 0.12, 0.025, 0, cx, top - 0.15, z + sz * w / 2, { mat: steelM, r: 0.008 });
  for (let x = x0 + 0.3; x < x1; x += 1.4) for (const sz of [-1, 1]) B(parent, 0.04, top - 0.15, 0.04, 0, x, 0, z + sz * (w / 2 - 0.02), { mat: steelM, r: 0.01 });
};
const bottleGuides = (parent, x0, x1, z) => {
  for (const sz of [-1, 1]) for (const y of [1.0, 1.12]) B(parent, x1 - x0, 0.012, 0.012, 0, (x0 + x1) / 2, y, z + sz * 0.058, { mat: steelM, r: 0.005, cast: false });
};

/* ---------- water treatment ---------- */
{
  const g = group(scene);
  const ss = M(0xd7dde3, { metal: 0.7, rough: 0.28 });
  for (const [x, z, r, h] of [[-18.2, -6.2, 0.95, 3.8], [-15.9, -6.6, 0.95, 3.8], [-13.6, -6.2, 0.8, 3.2]]){
    for (const a of [0.5, 2.6, 4.7]) B(g, 0.08, 0.6, 0.08, 0, x + Math.cos(a) * r * 0.75, 0, z + Math.sin(a) * r * 0.75, { mat: frameM });
    CY(g, r, h, 0, x, 0.6, z, { mat: ss, seg: 32 });
    const dome = mesh(g, new THREE.SphereGeometry(r, 32, 12, 0, TAU, 0, Math.PI / 2), ss, x, 0.6 + h, z); dome.scale.y = 0.35;
  }
  for (let i = 0; i < 3; i++){ CY(g, 0.28, 1.6, 0x4b78b7, -11.6 + i * 0.75, 0, -7.6, { rough: 0.4 }); CY(g, 0.29, 0.1, 0, -11.6 + i * 0.75, 1.6, -7.6, { mat: steelM }); }
  const pm = M(0xc9d0d7, { metal: 0.6, rough: 0.3 });
  pipe(g, V(-13.6, 3.6, -6.2), V(-9.0, 3.6, -6.2), 0.07, pm);
  pipe(g, V(-9.0, 3.6, -6.2), V(-9.0, 3.6, RF), 0.07, pm);
  pipe(g, V(-15.9, 3.0, -6.6), V(-13.6, 3.0, -6.2), 0.06, pm);
  machine('tanks', { root: g, name: 'Hệ thống xử lý nước', tab: 'Xử lý nước', anchor: V(-15.9, 5.4, -6.4),
    view: [V(-14.5, 2.2, -5.6), 11, 18, 18], foot: [-19.3, -7.8, -10.5, -5.0],
    rows: () => [['Công suất', '30 m³/giờ'], ['Màng lọc', 'RO 2 cấp'], ['TDS đầu ra', `${(7.6 + Math.sin(simT * 0.3) * 0.4).toFixed(1).replace('.', ',')} ppm`], ['Mức bồn thành phẩm', `${(78 + Math.sin(simT * 0.05) * 3).toFixed(0)}%`, 'blue'], ['Áp suất cấp', '0,32 MPa']] });
}

/* ---------- blow molder ---------- */
let moldWheel;
{
  const g = group(scene, -15.6, 0, 0);
  const cab = cabin(g, 4.2, 2.8, 2.5);
  B(g, 3.9, 0.55, 2.5, C.machine, 0, 0.32, 0, { r: 0.04 });
  moldWheel = group(g, 0.2, 0.9, 0);
  CY(moldWheel, 0.85, 0.18, 0, 0, 0, 0, { mat: steelM, seg: 32 });
  for (let i = 0; i < 12; i++){ const a = i / 12 * TAU; B(moldWheel, 0.16, 0.42, 0.2, 0, Math.cos(a) * 0.72, 0.18, Math.sin(a) * 0.72, { mat: darkM }); }
  CY(moldWheel, 0.12, 0.9, 0, 0, 0.18, 0, { mat: steelM });
  B(g, 0.9, 0.9, 0.7, C.white, -1.4, 0.32, 0.7, { r: 0.05 });           // oven
  B(g, 0.92, 0.12, 0.72, 0, -1.4, 0.95, 0.7, { mat: M(C.orange, { em: C.orange, ei: 0.5 }) });
  const hmi = group(g, 1.8, 0, 1.7); B(hmi, 0.08, 1.2, 0.08, 0, 0, 0, 0, { mat: frameM }); const sc = B(hmi, 0.5, 0.34, 0.04, 0, 0, 1.15, 0, { mat: M(0x0f172a) }); B(hmi, 0.44, 0.28, 0.01, 0, 0, 1.18, 0.022, { mat: M(0x1e3a8a, { em: 0x3b82f6, ei: 0.6 }), cast: false });
  // preform hopper + elevator
  B(g, 1.4, 1.3, 1.1, C.blue, -1.2, 0.5, -2.4, { rough: 0.5 });
  for (const sx of [-1, 1]) for (const sz of [-1, 1]) B(g, 0.07, 0.5, 0.07, 0, -1.2 + sx * 0.6, 0, -2.4 + sz * 0.45, { mat: frameM });
  pipe(g, V(-0.6, 1.4, -2.2), V(0.2, 2.6, -1.2), 0.12, M(C.yellow, { rough: 0.5 }));
  conveyorLegs(scene, -13.5, -9.15, 0, LINE_Y);
  bottleGuides(scene, -13.5, -9.15, 0);
  machine('blow', { root: g, name: 'Máy thổi chai', tab: 'Thổi chai', anchor: V(-15.6, 3.1, 0),
    view: [V(-15.0, 1.2, 0.2), 8.5, 22, 22], foot: [-17.7, -1.4, -13.5, 1.4],
    rows: () => [['Số khuôn', '12'], ['Nhiệt độ lò', `${(105 + Math.sin(simT) * 0.6).toFixed(1).replace('.', ',')} °C`], ['Áp suất thổi', `${fmt2(3.8 + Math.sin(simT * 1.7) * 0.03)} MPa`], ['Phôi chai', '28 g PET'], ['Tốc độ', `${fmt(rateNow())} chai/giờ`, 'blue']] });
}

/* ---------- filler / capper monoblock ---------- */
const FX = segF.cx, FZ = segF.cz, CXc = segC.cx, CZc = segC.cz;
let valveRods, valveNoz, valveBlk, fillTable, capHeads, capChuck, capTable, bowl, valveRing, capTop, guardPanels = [], capSorter;
const alM = M(0x9aa3ad, { metal: 0.6, rough: 0.35 });
const guardMat = M(0xd6eaf4, { rough: 0.08, metal: 0.1, op: 0.2, unique: true });
{
  const g = group(scene);
  // base table under monoblock
  B(g, 4.3, 0.8, 4.3, C.machine, -8.85, 0, 1.55, { r: 0.04 });
  B(g, 4.32, 0.08, 4.32, C.orange, -8.85, 0.12, 1.55, { r: 0.02 });
  // filler
  fillTable = group(g, FX, 0, FZ);
  CY(fillTable, RF + 0.07, 0.08, 0, 0, 0.8, 0, { mat: steelM, seg: 48 });
  for (let i = 0; i < NV; i++){ const a = i / NV * TAU; B(fillTable, 0.06, 0.015, 0.11, 0, Math.cos(a) * (RF + 0.03), 0.88, Math.sin(a) * (RF + 0.03), { mat: darkM, r: 0.004, cast: false }).rotation.y = -a; }
  CY(g, 0.22, 1.0, 0, FX, 0.88, FZ, { mat: steelM });
  valveRing = group(g, FX, 0, FZ);
  const vr = group(valveRing);
  valveRods = new THREE.InstancedMesh(cgeo(0.019, 0.019, 0.46, 10), M(0x3d434b, { rough: 0.45, metal: 0.4 }), NV);
  valveNoz = new THREE.InstancedMesh(cgeo(0.012, 0.022, 0.08, 10), M(0x1f2328, { rough: 0.5 }), NV);
  valveBlk = new THREE.InstancedMesh(rgeo(0.07, 0.11, 0.07, 0.01), M(C.steel, { metal: 0.5, rough: 0.35 }), NV);
  for (const im of [valveRods, valveNoz, valveBlk]){ im.castShadow = true; im.receiveShadow = true; im.frustumCulled = false; vr.add(im); }
  valveRods.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(NV * 3).fill(1), 3);
  bowl = group(g, FX, 0, FZ);
  CY(bowl, RF + 0.08, 0.32, 0, 0, 1.86, 0, { mat: M(0x4a5059, { metal: 0.45, rough: 0.35 }), seg: 48 });
  CY(bowl, RF - 0.12, 0.12, 0, 0, 2.18, 0, { mat: steelM, seg: 40 });
  CY(bowl, 0.08, 1.3, 0, 0, 2.3, 0, { mat: M(0xc9d0d7, { metal: 0.6, rough: 0.3 }) });
  // capper
  capTable = group(g, CXc, 0, CZc);
  CY(capTable, RC + 0.07, 0.08, 0, 0, 0.8, 0, { mat: steelM, seg: 32 });
  CY(g, 0.1, 1.05, 0, CXc, 0.88, CZc, { mat: steelM });
  capTop = group(g, CXc, 0, CZc);
  CY(capTop, RC + 0.07, 0.12, 0, 0, 1.78, 0, { mat: M(0x4a5059, { metal: 0.45, rough: 0.35 }), seg: 32 });
  const ch = group(capTop);
  capHeads = new THREE.InstancedMesh(cgeo(0.02, 0.02, 0.42, 10), M(0x8a929c, { metal: 0.5, rough: 0.35 }), NCAP);
  capChuck = new THREE.InstancedMesh(cgeo(0.03, 0.026, 0.07, 12), M(0x23272d, { rough: 0.5 }), NCAP);
  for (const im of [capHeads, capChuck]){ im.castShadow = true; im.frustumCulled = false; ch.add(im); }
  capHeads.userData.inner = ch;
  // cap sorter on a stand with chute
  capSorter = group(g, -7.55, 0, 3.75);
  for (const sx of [-1, 1]) for (const sz of [-1, 1]) B(capSorter, 0.06, 2.3, 0.06, 0, sx * 0.3, 0, sz * 0.3, { mat: frameM });
  CY(capSorter, 0.45, 0.28, 0, 0, 2.3, 0, { mat: steelM, seg: 32 });
  const capsIn = group(capSorter, 0, 2.5, 0); capSorter.userData.caps = capsIn;
  for (let i = 0; i < 26; i++){ const a = i * 2.4, r = 0.1 + (i % 4) * 0.08; CY(capsIn, 0.017, 0.022, C.cap, Math.cos(a) * r, 0, Math.sin(a) * r, { seg: 10, cast: false }); }
  pipe(g, V(-7.6, 2.45, 3.55), V(CXc + 0.15, 1.95, CZc + 0.05), 0.035, steelM);
  // glass guard (panels explode outward)
  const gx0 = -11.0, gx1 = -6.7, gz0 = -0.6, gz1 = 3.7, gy = 0.8, gh = 1.75;
  const addPanel = (x, z, len, axis, nx, nz) => {
    const pg = group(g, x, 0, z);
    const w = axis === 'x' ? len : 0.025, d = axis === 'x' ? 0.025 : len;
    B(pg, w, gh, d, 0, 0, gy, 0, { mat: guardMat, cast: false, r: 0.004 });
    B(pg, axis === 'x' ? len : 0.035, 0.035, axis === 'x' ? 0.035 : len, 0, 0, gy + gh, 0, { mat: alM, r: 0.008 });
    B(pg, 0.035, gh, 0.035, 0, axis === 'x' ? -len / 2 : 0, gy, axis === 'x' ? 0 : -len / 2, { mat: alM, r: 0.008 });
    guardPanels.push({ g: pg, nx, nz, x, z });
  };
  for (let x = gx0 + 0.55; x < gx1; x += 1.07) { addPanel(x, gz0, 1.07, 'x', 0, -1); addPanel(x, gz1, 1.07, 'x', 0, 1); }
  for (const [z, len] of [[(0.25 + 1.4) / 2, 1.15], [2.05, 1.05], [3.2, 1.0]]) addPanel(gx0, z, len, 'z', -1, 0);
  for (const [z, len] of [[0.2, 1.6], [1.6, 1.2], [3.5, 0.4]]) addPanel(gx1, z, len, 'z', 1, 0);
  const hmi = group(scene, -7.6, 0, 4.15); B(hmi, 0.08, 1.2, 0.08, 0, 0, 0, 0, { mat: frameM }); B(hmi, 0.55, 0.36, 0.05, 0, 0, 1.15, 0, { mat: M(0x0f172a) }); B(hmi, 0.48, 0.3, 0.01, 0, 0, 1.18, 0.028, { mat: M(0x1e3a8a, { em: 0x3b82f6, ei: 0.6 }), cast: false });
  machine('filler', { root: g, name: 'Chiết rót & đóng nắp', tab: 'Chiết rót & đóng nắp', anchor: V(-8.85, 3.4, 1.5),
    view: [V(-8.9, 1.15, 1.7), 9.5, 16, 30], foot: [-11.0, -0.6, -6.7, 3.7],
    rows: () => [['Van chiết', '60'], ['Đầu đóng nắp', '18'], ['Thể tích chiết', '1.500 ± 5 ml'], ['Áp suất van', sim.alarm ? 'Van #24 thấp' : '0,18 MPa', sim.alarm ? 'bad' : ''],
      ['Nhiệt độ nước', `${(18.2 + Math.sin(simT * 0.4) * 0.15).toFixed(1).replace('.', ',')} °C`], ['Tốc độ', `${fmt(rateNow())} chai/giờ`, 'blue']] });
}
conveyorLegs(scene, segOut.x0 + 0.25, X_END, ZL, LINE_Y);
bottleGuides(scene, -6.7, X_END, ZL);

/* ---------- light inspection + reject ---------- */
let inspPanel, inspCam, pusher, towerLights, rejectBin;
{
  const g = group(scene, X_INSP, 0, ZL);
  for (const sz of [-1, 1]) B(g, 0.08, 1.95, 0.08, 0, 0, 0, sz * 0.42, { mat: frameM });
  B(g, 0.14, 0.1, 0.96, 0, 0, 1.95, 0, { mat: frameM });
  inspPanel = B(g, 0.6, 0.44, 0.04, 0, 0, 0.88, -0.2, { mat: M(0xffffff, { em: 0xffffff, ei: 0.6, unique: true }) });
  inspCam = B(g, 0.2, 0.16, 0.28, C.white, 0, 1.18, 0.34, { r: 0.03 });
  CY(g, 0.035, 0.05, 0, 0, 1.24, 0.19, { mat: M(0x111111), seg: 12 }).rotation.x = Math.PI / 2;
  towerLights = [0x22c55e, 0xf59e0b, 0xef4444].map((c, i) => CY(g, 0.045, 0.07, 0, 0, 2.05 + i * 0.075, -0.42, { mat: M(c, { em: c, ei: i ? 0.05 : 1.2, unique: true }), seg: 14 }));
  // reject
  const r = group(scene, X_REJ, 0, ZL);
  B(r, 0.2, 0.16, 0.16, 0, 0, 0.92, -0.3, { mat: M(C.red, { rough: 0.45 }) });
  pusher = B(r, 0.12, 0.05, 0.3, 0, 0, 0.97, -0.2, { mat: M(C.red, { rough: 0.45 }) });
  pusher.geometry = rgeo(0.12, 0.05, 1, 0.01); pusher.scale.z = 0.08;
  B(r, 0.7, 0.03, 0.55, 0, 0.1, LINE_Y - 0.03, 0.42, { mat: steelM });
  for (const [x, z, w, d] of [[0.1, 0.7, 0.7, 0.03], [-0.25, 0.42, 0.03, 0.55], [0.45, 0.42, 0.03, 0.55]]) B(r, w, 0.08, d, C.orange, x, LINE_Y, z, { r: 0.008 });
  for (const sx of [-1, 1]) B(r, 0.04, LINE_Y - 0.03, 0.04, 0, 0.1 + sx * 0.3, 0, 0.65, { mat: steelM });
  rejectBin = B(r, 0.5, 0.45, 0.4, 0x3b4048, 0.1, 0, 0.95, { r: 0.04 });
  const st = group(scene, X_INSP - 0.2, 0, ZL + 1.1); B(st, 0.06, 1.1, 0.06, 0, 0, 0, 0, { mat: frameM }); B(st, 0.4, 0.28, 0.05, 0, 0, 1.08, 0, { mat: M(0x0f172a) }); B(st, 0.34, 0.22, 0.01, 0, 0, 1.11, 0.028, { mat: M(0x1e3a8a, { em: 0x3b82f6, ei: 0.6 }), cast: false });
  machine('insp', { root: g, name: 'Soi đèn & loại lỗi', tab: 'Soi đèn & loại', anchor: V(X_INSP + 0.3, 2.45, ZL),
    view: [V(X_INSP + 0.35, 1.0, ZL + 0.1), 4.4, 26, 24], foot: [X_INSP - 0.5, ZL - 0.5, X_REJ + 0.6, ZL + 1.2],
    rows: () => [['Camera', '4 góc'], ['Đã kiểm', fmt(inspected())], ['Đã loại', fmt(sim.rejects), sim.rejects ? 'bad' : ''], ['Tỉ lệ lỗi', `${fmt2(sim.rejects / Math.max(1, inspected()) * 100)}%`], ['Lần NG gần nhất', sim.lastNG || '—']] });
  MACH.insp.root2 = r; r.traverse(o => o.userData.mid = 'insp'); pickRoots.push(r);
}

/* ---------- labeler ---------- */
let labelDrum, labelRolls = [];
{
  const g = group(scene, X_LABEL, 0, ZL);
  B(g, 1.3, 1.0, 0.7, C.machine, 0, 0, -0.62, { r: 0.04 });
  B(g, 1.32, 0.07, 0.72, C.orange, 0, 0.15, -0.62, { r: 0.02 });
  labelDrum = CY(g, 0.15, 0.22, 0, 0, 0.88, -0.2, { mat: steelM, seg: 20 });
  for (const sx of [-0.33, 0.3]){ const rr = group(g, sx, 1.0, -0.62); CY(rr, 0.25, 0.16, C.white, 0, 0, 0, { seg: 32 }); CY(rr, 0.07, 0.17, C.blue, 0, 0, 0, { seg: 16 }); B(rr, 0.03, 0.17, 0.12, C.blue, 0.2, 0, 0, { r: 0.01 }); labelRolls.push(rr); }
  // sleeve shrink tunnel
  B(g, 1.0, 0.55, 0.42, 0xd9dee4, 1.15, LINE_Y - 0.05, 0, { metal: 0.4, rough: 0.35 });
  B(g, 0.02, 0.38, 0.25, 0, 0.64, LINE_Y, 0, { mat: M(C.orange, { em: C.orange, ei: 0.7 }), cast: false });
  machine('label', { root: g, name: 'Dán nhãn & co nhiệt', tab: 'Dán nhãn', anchor: V(X_LABEL + 0.4, 2.0, ZL - 0.4),
    view: [V(X_LABEL + 0.3, 1.0, ZL - 0.2), 4.4, 18, 24], foot: [X_LABEL - 0.7, ZL - 1.0, X_LABEL + 1.7, ZL + 0.25],
    rows: () => [['Loại nhãn', 'Màng co PVC'], ['Cuộn nhãn còn', `${(64 - (simT * 0.02) % 40).toFixed(0)}%`], ['Sai lệch vị trí', '± 0,4 mm'], ['Nhiệt độ hầm co', '165 °C'], ['Tốc độ', `${fmt(rateNow())} chai/giờ`, 'blue']] });
}
// crossover stair over the line (yellow)
{
  const g = group(scene, X_LABEL + 3.1, 0, ZL);
  const ym = M(C.yellow, { rough: 0.5 });
  const flight = (sz) => { for (let i = 0; i < 11; i++) B(g, 0.8, 0.04, 0.22, 0x8b929b, 0, i * 0.2 + 0.18, sz * (1.6 - i * 0.12), { metal: 0.4, rough: 0.5, r: 0.008 });
    for (const sx of [-1, 1]) pipe(g, V(sx * 0.42, 1.0, sz * 1.75), V(sx * 0.42, 3.2, sz * 0.4), 0.025, ym); };
  flight(1); flight(-1);
  B(g, 0.9, 0.06, 0.8, 0x8b929b, 0, 2.2, 0, { metal: 0.4, rough: 0.5 });
  for (const sx of [-1, 1]) B(g, 0.05, 1.0, 0.8, C.yellow, sx * 0.45, 2.26, 0, { mat: ym });
  for (const sx of [-1, 1]) for (const sz of [-1, 1]) B(g, 0.06, 2.2, 0.06, 0, sx * 0.4, 0, sz * 0.36, { mat: frameM });
}

/* ---------- shrink wrapper ---------- */
let tunnelGlow;
{
  const g = group(scene, 0, 0, ZL);
  const cab = cabin(g, 3.0, 1.6, 2.2); cab.position.x = X_END + 1.5;
  B(g, 2.8, 0.55, 1.4, C.machine, X_END + 1.5, 0.32, 0, { r: 0.04 });
  CY(g, 0.18, 1.2, 0, X_END + 2.1, 0.35, -0.55, { mat: M(0xe7f1f8, { rough: 0.3 }), seg: 20 }).rotation.x = Math.PI / 2;
  B(g, 2.0, 1.15, 1.0, 0xd5dbe1, X_END + 4.1, 0, 0, { metal: 0.45, rough: 0.32 });
  tunnelGlow = B(g, 0.03, 0.42, 0.55, 0, X_END + 3.09, PACK_Y, 0, { mat: M(C.orange, { em: C.orange, ei: 1.2, unique: true }), cast: false });
  B(g, 0.03, 0.42, 0.55, 0, X_END + 5.11, PACK_Y, 0, { mat: tunnelGlow.material, cast: false });
  B(g, 2.02, 0.1, 1.02, C.orange, X_END + 4.1, 0.2, 0, { r: 0.02 });
  machine('wrap', { root: g, name: 'Màng co thành lốc', tab: 'Màng co', anchor: V(X_END + 2.6, 2.75, ZL),
    view: [V(X_END + 3.0, 1.0, ZL), 7.2, 16, 24], foot: [X_END, ZL - 0.8, X_END + 5.1, ZL + 0.8],
    rows: () => [['Quy cách', '12 chai/lốc (3×4)'], ['Màng co', 'PE 60 µm'], ['Nhiệt độ hầm', `${(185 + Math.sin(simT * 0.6) * 1.2).toFixed(0)} °C`], ['Lốc/phút', fmt1(rateNow() / 12 / 60), 'blue'], ['Lốc hôm nay', fmt(Math.floor(sim.S / (12 * P)) + 15000)]] });
}
// pack roller conveyor
{
  const x0 = X_END + 5.1, x1 = PACK_X0 + LP + 0.25, len = x1 - x0, cx = (x0 + x1) / 2;
  for (const sz of [-1, 1]) B(scene, len, 0.1, 0.04, 0, cx, PACK_Y - 0.12, ZL + sz * 0.26, { mat: steelM });
  const rollers = new THREE.InstancedMesh(cgeo(0.025, 0.025, 0.5, 10), steelM, Math.floor(len / 0.1));
  const q = new THREE.Quaternion().setFromAxisAngle(V(1, 0, 0), Math.PI / 2), m4 = new THREE.Matrix4();
  for (let i = 0; i < rollers.count; i++){ m4.compose(V(x0 + 0.05 + i * 0.1, PACK_Y - 0.026, ZL), q, V(1, 1, 1)); rollers.setMatrixAt(i, m4); }
  rollers.receiveShadow = true; scene.add(rollers);
  for (let x = x0 + 0.3; x < x1; x += 1.3) for (const sz of [-1, 1]) B(scene, 0.04, PACK_Y - 0.12, 0.04, 0, x, 0, ZL + sz * 0.24, { mat: steelM });
  for (const sz of [-1, 1]) B(scene, len, 0.04, 0.02, C.orange, cx, PACK_Y + 0.08, ZL + sz * 0.22, { r: 0.008 });
}

/* ---------- palletizing robot ---------- */
const RB = V(12.5, 0, 1.55), SH = 1.0, L1 = 1.2, L2 = 1.1, TOOL = 0.3, PACK_H = 0.33;
const PAL = V(14.05, 0, 0.75);
const robot = {};
{
  const g = group(scene, RB.x, 0, RB.z);
  const om = M(C.orange, { rough: 0.42, metal: 0.1 }), jm = M(0x2b2f36, { rough: 0.5, metal: 0.3 });
  B(g, 0.8, 0.3, 0.8, 0, 0, 0, 0, { mat: jm });
  robot.turret = group(g, 0, 0.3, 0);
  CY(robot.turret, 0.34, 0.32, 0, 0, 0, 0, { mat: om, seg: 28 });
  B(robot.turret, 0.42, 0.42, 0.4, 0, 0.05, 0.32, 0, { mat: om, r: 0.08 });
  robot.upper = group(robot.turret, 0, SH - 0.3, 0);
  CY(robot.upper, 0.17, 0.46, 0, 0, -0.23, 0, { mat: jm, seg: 20 }).rotation.x = Math.PI / 2;
  B(robot.upper, L1, 0.24, 0.22, 0, L1 / 2, -0.12, 0, { mat: om, r: 0.08 });
  robot.fore = group(robot.upper, L1, 0, 0);
  CY(robot.fore, 0.13, 0.36, 0, 0, -0.18, 0, { mat: jm, seg: 18 }).rotation.x = Math.PI / 2;
  B(robot.fore, L2, 0.17, 0.16, 0, L2 / 2, -0.085, 0, { mat: om, r: 0.06 });
  robot.wrist = group(robot.fore, L2, 0, 0);
  CY(robot.wrist, 0.08, 0.2, 0, 0, -0.1, 0, { mat: jm, seg: 14 }).rotation.x = Math.PI / 2;
  B(robot.wrist, TOOL - 0.05, 0.1, 0.1, 0, (TOOL - 0.05) / 2, -0.05, 0, { mat: jm, r: 0.02 });
  const grip = group(robot.wrist, TOOL - 0.03, 0, 0);
  B(grip, 0.04, 0.42, 0.36, 0, 0, -0.21, 0, { mat: M(0x9aa3ad, { metal: 0.5, rough: 0.35 }), r: 0.01 }).rotation.z = Math.PI / 2;
  robot.fingers = [-1, 1].map(s => { const f = group(grip, 0, 0, s * 0.17); B(f, 0.3, 0.03, 0.03, 0, 0.13, -0.015, 0, { mat: jm, r: 0.008 }); return f; });
  // pallet
  B(scene, 1.2, 0.15, 1.0, C.wood, PAL.x, 0, PAL.z, { rough: 0.8 });
  // safety fence
  const fm = M(0x2b2f36, { op: 0.25, rough: 0.6 }), ym = M(C.yellow, { rough: 0.5 });
  const fence = (x0, z0, x1, z1) => {
    const len = Math.hypot(x1 - x0, z1 - z0), n = Math.round(len / 1.2);
    for (let i = 0; i <= n; i++){ const k = i / n; B(scene, 0.06, 1.7, 0.06, 0, lerp(x0, x1, k), 0, lerp(z0, z1, k), { mat: ym }); }
    const p = B(scene, len, 1.4, 0.02, 0, (x0 + x1) / 2, 0.2, (z0 + z1) / 2, { mat: fm, cast: false }); p.rotation.y = -Math.atan2(z1 - z0, x1 - x0);
  };
  fence(11.0, -0.7, 15.4, -0.7); fence(15.4, -0.7, 15.4, 2.2);
  machine('robot', { root: g, name: 'Robot xếp pallet', tab: 'Xếp pallet', anchor: V(RB.x + 0.6, 3.1, RB.z),
    view: [V(13.1, 1.0, 1.7), 7.2, -24, 24], foot: [11.0, -0.7, 15.4, 3.6],
    rows: () => { const st = palletState(); return [['Tải trọng', '180 kg · 6 trục'], ['Chu kỳ', `${fmt1(PACK_P / Math.max(0.01, 0.4 * VNOM * sim.speed * sim.rate))} s`, 'blue'], ['Lớp hiện tại', `${st.layer} / 4`], ['Lốc trên pallet', `${st.n} / 36`], ['Pallet hôm nay', fmt(st.pallets)]]; } });
}

/* ---------- warehouse racking + finished pallets ---------- */
const forklift = {};
{
  const g = group(scene);
  const blueM = M(0x2563eb, { rough: 0.5, metal: 0.2 }), orM = M(C.orange, { rough: 0.5 });
  const fullPallet = (parent, x, y, z) => { B(parent, 1.2, 0.15, 1.0, C.wood, x, y, z, { rough: 0.8 }); B(parent, 1.14, 1.32, 0.94, C.film, x, y + 0.15, z, { rough: 0.3, r: 0.04 });
    for (let i = 0; i < 4; i++) B(parent, 1.15, 0.015, 0.95, 0x9cc3e6, x, y + 0.45 + i * 0.33, z, { cast: false, r: 0.004 }); };
  for (let bay = 0; bay < 4; bay++){
    const x = 8.6 + bay * 2.8;
    for (const dx of [-1.35, 1.35]) for (const dz of [-0.5, 0.5]) B(g, 0.08, 5.0, 0.08, 0, x + dx, 0, -8.0 + dz, { mat: blueM });
    for (const y of [1.8, 3.6]) for (const dz of [-0.5, 0.5]) B(g, 2.7, 0.12, 0.08, 0, x, y, -8.0 + dz, { mat: orM });
    for (const [lv, y] of [[0, 0], [1, 1.92], [2, 3.72]]) if ((bay + lv) % 3 !== 2) fullPallet(g, x, y, -8.0);
  }
  for (let r = 0; r < 3; r++) for (let c = 0; c < 2; c++) fullPallet(g, 17.4 + c * 1.5, 0, -3.6 + r * 1.4);
  // forklift
  const f = forklift.g = group(scene, 16.6, 0, 1.0);
  const fy = M(C.yellow, { rough: 0.5 }), fd = M(0x2b2f36, { rough: 0.5 });
  B(f, 1.1, 0.55, 0.9, 0, 0, 0.18, 0, { mat: fy, r: 0.08 });
  B(f, 0.5, 0.45, 0.85, 0, -0.35, 0.73, 0, { mat: fd, r: 0.06 });
  for (const sx of [-1, 1]) for (const sz of [-1, 1]) B(f, 0.06, 1.3, 0.06, 0, sx * 0.35 - 0.15, 0.73, sz * 0.42, { mat: fd });
  B(f, 0.8, 0.06, 0.92, 0, -0.15, 2.03, 0, { mat: fd });
  for (const sx of [-1, 1]) for (const sz of [-1, 1]) CY(f, 0.18, 0.14, 0, sx * 0.38, 0.18, sz * 0.46, { mat: fd, seg: 16 }).rotation.x = Math.PI / 2;
  const mast = group(f, 0.62, 0, 0); B(mast, 0.08, 2.0, 0.6, 0, 0, 0, 0, { mat: fd });
  forklift.carriage = group(mast, 0.1, 0.12, 0);
  for (const sz of [-0.22, 0.22]) B(forklift.carriage, 1.0, 0.05, 0.12, 0, 0.5, 0, sz, { mat: fd });
  forklift.load = group(forklift.carriage, 0.55, 0.05, 0); fullPallet(forklift.load, 0, 0, 0); forklift.load.rotation.y = Math.PI / 2;
  const drv = person(C.suit); drv.g.position.set(-0.3, 0.55, 0); drv.g.scale.setScalar(1.55); f.add(drv.g);
  drv.legs.forEach(l => l.rotation.z = Math.PI / 2.2);
  machine('store', { root: g, name: 'Kho thành phẩm', tab: 'Kho', anchor: V(13.0, 5.6, -8.0),
    view: [V(14.0, 1.4, -4.0), 12, -20, 26], foot: [7.0, -8.8, 19.6, -2.0],
    rows: () => [['Pallet trong kho', fmt(214 + palletState().pallets % 40)], ['Kệ chứa', '4 dãy × 3 tầng'], ['Xe nâng', '1 đang chạy', 'blue'], ['Xuất hôm nay', '86 pallet']] });
}

/* ---------- control room on mezzanine ---------- */
{
  const g = group(scene, 1.0, 0, -6.2);
  const ym = M(C.yellow, { rough: 0.5 });
  for (const sx of [-1, 1]) for (const sz of [-1, 1]) B(g, 0.2, 3.0, 0.2, 0, sx * 3.2, 0, sz * 1.8, { mat: frameM });
  B(g, 6.8, 0.2, 4.0, 0x8b929b, 0, 3.0, 0, { metal: 0.3, rough: 0.6 });
  for (const sx of [-1, 1]) for (const sz of [-1, 1]) B(g, 0.08, 2.4, 0.08, 0, sx * 2.6, 3.2, sz * 1.45, { mat: frameM });
  B(g, 5.2, 2.4, 0.02, 0, 0, 3.2, 1.45, { mat: glassM, cast: false });
  B(g, 0.02, 2.4, 2.9, 0, 2.6, 3.2, 0, { mat: glassM, cast: false });
  B(g, 0.02, 2.4, 2.9, 0, -2.6, 3.2, 0, { mat: M(C.wall) });
  const roofM = M(C.white, { rough: 0.55, unique: true }); housingMats.push(roofM);
  B(g, 5.5, 0.15, 3.2, 0, 0, 5.6, 0, { mat: roofM });
  B(g, 3.2, 0.75, 0.6, 0xe4e7eb, -0.4, 3.2, 0.6, { r: 0.04 });
  for (let i = 0; i < 4; i++){ const sc = B(g, 0.6, 0.38, 0.04, 0, -1.6 + i * 0.75, 4.0, 0.42, { mat: M(0x0f172a) }); B(g, 0.54, 0.32, 0.01, 0, -1.6 + i * 0.75, 4.03, 0.445, { mat: M(i === 1 ? 0x7c2d12 : 0x1e3a8a, { em: i === 1 ? 0xf97316 : 0x3b82f6, ei: 0.5 }), cast: false }); }
  B(g, 6.8, 0.05, 0.05, 0, 0, 4.15, 2.0, { mat: ym }); B(g, 6.8, 0.05, 0.05, 0, 0, 3.65, 2.0, { mat: ym });
  for (let x = -3.3; x <= 3.4; x += 1.1) B(g, 0.05, 0.95, 0.05, 0, x, 3.2, 2.0, { mat: ym });
  // stair down to floor
  for (let i = 0; i < 15; i++) B(g, 0.9, 0.05, 0.26, 0x8b929b, 3.85, 0.2 * i + 0.15, 2.0 + 0.27 * (15 - i), { metal: 0.4, rough: 0.5, r: 0.008 });
  for (const sx of [-1, 1]) pipe(g, V(3.85 + sx * 0.47, 1.0, 6.2), V(3.85 + sx * 0.47, 4.15, 2.1), 0.025, ym);
  const op = person(C.suit); op.g.scale.setScalar(1.6); op.g.position.set(-0.4, 3.2, 1.25); op.g.rotation.y = -Math.PI / 2; g.add(op.g); op.arms.forEach(a => a.rotation.z = 0.9);
  machine('control', { root: g, name: 'Phòng điều khiển', tab: 'Điều khiển', anchor: V(1.0, 6.3, -6.2),
    view: [V(0.6, 4.2, -5.8), 8.0, 10, 14], foot: [-2.4, -8.2, 4.4, -4.2],
    rows: () => [['Ca làm việc', 'Ca 1 · 06:00–14:00'], ['Người trực', '2'], ['Cảnh báo đang mở', sim.alarm || sim.estop ? '1' : '0', sim.alarm || sim.estop ? 'bad' : ''], ['Kết nối PLC', '7 / 7 máy', 'blue']] });
}

/* ---------- people ---------- */
function person(suit){
  const g = new THREE.Group();
  const sk = M(C.skin, { rough: 0.7 }), su = M(suit, { rough: 0.7 }), hel = M(0xf8fafc, { rough: 0.4 });
  const legs = [];
  for (const sz of [-0.075, 0.075]){ const lg = new THREE.Group(); lg.position.set(0, 0.34, sz); B(lg, 0.12, 0.34, 0.11, 0, 0, -0.34, 0, { mat: su }); g.add(lg); legs.push(lg); }
  B(g, 0.22, 0.4, 0.32, 0, 0, 0.33, 0, { mat: su, r: 0.07 });
  B(g, 0.23, 0.06, 0.33, 0, 0, 0.5, 0, { mat: M(C.orange, { rough: 0.6 }), cast: false });
  const arms = [];
  for (const sz of [-0.2, 0.2]){ const ag = new THREE.Group(); ag.position.set(0, 0.68, sz); B(ag, 0.1, 0.3, 0.08, 0, 0, -0.3, 0, { mat: su }); g.add(ag); arms.push(ag); }
  B(g, 0.19, 0.19, 0.19, 0, 0, 0.74, 0, { mat: sk, r: 0.06 });
  B(g, 0.23, 0.09, 0.23, 0, 0, 0.9, 0, { mat: hel, r: 0.06 });
  B(g, 0.08, 0.02, 0.2, 0, 0.13, 0.9, 0, { mat: hel, r: 0.008 });
  return { g, legs, arms };
}
const walkers = [];
function addWalker(pts, speed, suit, off = 0){
  const p = person(suit); p.g.scale.setScalar(1.62); scene.add(p.g);
  let L = 0; const seg = []; for (let i = 0; i < pts.length; i++){ const a = pts[i], b = pts[(i + 1) % pts.length]; const l = Math.hypot(b[0] - a[0], b[1] - a[1]); seg.push({ a, b, l, s0: L }); L += l; }
  walkers.push({ p, seg, L, speed, off });
}
addWalker([[-17, 7.7], [9, 7.7], [9, 7.1], [-17, 7.1]], 1.0, C.suit, 0);
addWalker([[-5.8, 1.4], [0.6, 1.4], [0.6, 1.0], [-5.8, 1.0]], 0.8, 0x1f2937, 4);
addWalker([[-12.2, -2.6], [-6.4, -2.6], [-6.4, -3.2], [-12.2, -3.2]], 0.7, C.suit, 2);
const standers = [];
for (const [x, z, yaw, c] of [[X_INSP - 1.3, ZL - 1.3, -Math.PI / 2.6, C.suit], [-7.6, 4.6, Math.PI / 2, 0x1f2937], [-3.1, -8.1, Math.PI / 2, C.suit], [11.2, 4.4, 0.5, C.suit]]){
  const p = person(c); p.g.scale.setScalar(1.62); p.g.position.set(x, 0, z); p.g.rotation.y = yaw; scene.add(p.g); standers.push(p);
}

/* ================= bottles (instanced) ================= */
const bottleGeo = new THREE.LatheGeometry([[0, 0], [0.038, 0], [0.045, 0.012], [0.045, 0.205], [0.041, 0.232], [0.03, 0.27], [0.017, 0.294], [0.015, 0.305], [0.0, 0.306]].map(p => new THREE.Vector2(p[0], p[1])), 18);
const waterGeo = new THREE.LatheGeometry([[0, 0.004], [0.04, 0.006], [0.042, 0.02], [0.042, 0.2], [0.038, 0.23], [0.0, 0.232]].map(p => new THREE.Vector2(p[0], p[1])), 16);
const capGeo = new THREE.CylinderGeometry(0.0175, 0.0175, 0.022, 14); capGeo.translate(0, 0.011, 0);
const labelGeo = new THREE.CylinderGeometry(0.0462, 0.0462, 0.09, 18, 1, true); labelGeo.translate(0, 0.045, 0);
const NB = Math.ceil((LPATH + 4.5) / P) + 6;
const bottleMat = new THREE.MeshStandardMaterial({ color: 0xe3f1fa, roughness: 0.08, metalness: 0, transparent: true, opacity: 0.42, depthWrite: false });
const waterMat = new THREE.MeshStandardMaterial({ color: 0x7cc0ea, roughness: 0.15, transparent: true, opacity: 0.6, depthWrite: false });
const bodies = new THREE.InstancedMesh(bottleGeo, bottleMat, NB);
const waters = new THREE.InstancedMesh(waterGeo, waterMat, NB);
const caps = new THREE.InstancedMesh(capGeo, M(C.cap, { rough: 0.4 }), NB);
const labels = new THREE.InstancedMesh(labelGeo, M(0x2d7be0, { rough: 0.45 }), NB);
for (const im of [bodies, waters, caps, labels]){ im.frustumCulled = false; im.castShadow = im !== waters; im.receiveShadow = true; scene.add(im); }
bodies.userData.bottles = true;

/* ================= packs (pool) ================= */
const NPACK = 64;
const packPool = [];
{
  const film = M(0xe6f1f9, { rough: 0.22 }), inner = M(0x9fcdee, { rough: 0.3 });
  const capG = new THREE.CylinderGeometry(0.017, 0.017, 0.02, 10);
  for (let i = 0; i < NPACK; i++){
    const g = new THREE.Group(); g.visible = false; scene.add(g);
    B(g, 0.36, 0.3, 0.27, 0, 0, 0, 0, { mat: inner, r: 0.035 });
    B(g, 0.37, 0.12, 0.28, 0, 0, 0.09, 0, { mat: film, r: 0.03 });
    const ic = new THREE.InstancedMesh(capG, caps.material, 12); const m4 = new THREE.Matrix4(); let k = 0;
    for (const x of [-0.135, -0.045, 0.045, 0.135]) for (const z of [-0.09, 0, 0.09]) { m4.makeTranslation(x, 0.315, z); ic.setMatrixAt(k++, m4); }
    ic.castShadow = true; g.add(ic);
    packPool.push(g);
  }
}

/* ================= simulation ================= */
const VNOM = 24000 / 3600 * P;            // m/s at rated speed
const S0 = 260;
const sim = { S: S0, speed: 1, rate: 1, paused: false, estop: false, alarm: false, explode: 0, explodeTarget: 0, rejects: 37, defects: new Set(), passedInsp: new Set(), lastNG: '', xray: false };
let simT = 0;
const rateNow = () => Math.round(24000 * sim.speed / 10) * 10;
const inspected = () => Math.max(0, Math.floor((sim.S - S_INSP) / P)) - Math.floor((S0 - S_INSP) / P) + 182400;
const serialOf = n => 15000 + n;
function palletState(){
  const made = Math.floor((sim.S - S_END) / (12 * P));
  let placed = -1;
  for (let j = made - 1; j >= Math.max(0, made - 20); j--){ const u = (sim.S - (S_END + 12 * P * (j + 1))) * 0.4; if (u >= LP + PACK_P * 0.68){ placed = j; break; } }
  const n = placed < 0 ? 0 : (placed % 36) + 1;
  return { placed, n, layer: Math.min(4, Math.floor((n - 1) / 9) + 1) || 1, pallets: 120 + Math.floor((placed + 1) / 36) };
}

const _m = new THREE.Matrix4(), _q = new THREE.Quaternion(), _p = new THREE.Vector3(), _s = new THREE.Vector3(), _o = {};
const HIDE = new THREE.Matrix4().compose(V(0, -50, 0), _q, V(0.001, 0.001, 0.001));
function bottlePos(n, out){
  const s = sim.S - n * P;
  if (sim.defects.has(n) && s >= S_REJ){
    if (s > S_REJ + 4) return null;
    const k = smooth((s - S_REJ) / 0.3);
    out.set(X_REJ + 0.12 * k, LINE_Y, ZL + 0.5 * k); out.s = s; return out;
  }
  if (s < 0 || s > S_END + 0.02) return null;
  path.at(s, _o); out.set(_o.x, LINE_Y, _o.z); out.s = s; return out;
}
const _bp = new THREE.Vector3();
function updateBottles(){
  const S = sim.S, nMax = Math.floor(S / P), nMin = Math.ceil((S - S_END - 4.2) / P);
  for (let i = 0; i < NB; i++){ bodies.setMatrixAt(i, HIDE); waters.setMatrixAt(i, HIDE); caps.setMatrixAt(i, HIDE); labels.setMatrixAt(i, HIDE); }
  for (let n = nMin; n <= nMax; n++){
    const p = bottlePos(n, _bp); if (!p) continue;
    const s = p.s, slot = mod(n, NB);
    _m.compose(p, _q, _s.set(1, 1, 1)); bodies.setMatrixAt(slot, _m);
    const f = clamp01((s - S_FILL0) / (S_FILL1 - S_FILL0));
    if (f > 0.001){ _m.compose(p, _q, _s.set(1, f, 1)); waters.setMatrixAt(slot, _m); }
    if (s >= S_CAP && !sim.defects.has(n)){ const d = 1 - smooth((s - S_CAP) / 0.12); _p.copy(p); _p.y += 0.293 + d * 0.06; _m.compose(_p, _q, _s.set(1, 1, 1)); caps.setMatrixAt(slot, _m); }
    if (s >= S_LABEL && !(sim.defects.has(n) && s >= S_REJ)){ _p.copy(p); _p.y += 0.09; const k = smooth((s - S_LABEL) / 0.08); _m.compose(_p, _q, _s.set(1, Math.max(0.01, k), 1)); labels.setMatrixAt(slot, _m); }
  }
  for (const im of [bodies, waters, caps, labels]) im.instanceMatrix.needsUpdate = true;
}

// filler + capper rotation, valve lowering
const _vm = new THREE.Matrix4(), _vp = new THREE.Vector3();
const fillArc = [segF, S_FILL0, S_FILL1];
function polarOn(seg, l){ path.on(seg, l, _o); return Math.atan2(_o.z - seg.cz, _o.x - seg.cx); }
const angF0 = polarOn(segF, S_FILL0 - segF.s0), angF1 = polarOn(segF, S_FILL1 - segF.s0);
function angBetween(a, a0, a1){ // is angle a on the arc from a0 to a1 going ccw (increasing)?
  const span = mod(a1 - a0, TAU), d = mod(a - a0, TAU); return d <= span ? d / span : -1;
}
function updateMachines(dt){
  const S = sim.S;
  // filler: valve 0 tracks virtual bottle n=0
  const yF = -polarOn(segF, S - segF.s0);
  valveRing.rotation.y = yF; fillTable.rotation.y = yF;
  for (let i = 0; i < NV; i++){
    const a = i / NV * TAU, wa = a - yF;
    const k = angBetween(mod(wa + Math.PI, TAU) - Math.PI, angF0, angF1);
    const low = k >= 0 ? Math.sin(Math.PI * Math.min(1, k * 1.15)) * 0 + 1 : 0;
    const ramp = k >= 0 ? Math.min(1, k / 0.08, (1 - k) / 0.08) : 0;
    const dy = -0.06 * ramp;
    const x = Math.cos(a) * RF, z = Math.sin(a) * RF;
    _vm.makeTranslation(x, 1.52 + dy, z); valveRods.setMatrixAt(i, _vm);
    _vm.makeTranslation(x, 1.27 + dy, z); valveNoz.setMatrixAt(i, _vm);
    _vm.makeTranslation(x, 1.78, z); valveBlk.setMatrixAt(i, _vm);
  }
  valveRods.instanceMatrix.needsUpdate = valveNoz.instanceMatrix.needsUpdate = valveBlk.instanceMatrix.needsUpdate = true;
  // capper: head 0 tracks bottle n=0 on capper arc
  const yC = -polarOn(segC, S - segC.s0);
  capHeads.userData.inner.rotation.y = yC; capTable.rotation.y = yC;
  const c0 = polarOn(segC, 0.3 * segC.len), c1 = polarOn(segC, 0.75 * segC.len);
  for (let i = 0; i < NCAP; i++){
    const a = i / NCAP * TAU, wa = mod(a - yC + Math.PI, TAU) - Math.PI;
    const k = angBetween(wa, c1, c0); // capper runs clockwise: reverse bounds
    const ramp = k >= 0 ? Math.min(1, k / 0.15, (1 - k) / 0.15) : 0;
    const x = Math.cos(a) * RC, z = Math.sin(a) * RC;
    _vm.makeTranslation(x, 1.57 - 0.06 * ramp, z); capHeads.setMatrixAt(i, _vm);
    _vm.makeTranslation(x, 1.33 - 0.06 * ramp, z); capChuck.setMatrixAt(i, _vm);
  }
  capHeads.instanceMatrix.needsUpdate = capChuck.instanceMatrix.needsUpdate = true;
  capSorter.userData.caps.rotation.y += dt * sim.speed * sim.rate * 1.5;
  moldWheel.rotation.y -= dt * sim.speed * sim.rate * 0.9;
  labelDrum.rotation.y += dt * sim.speed * sim.rate * 5;
  labelRolls.forEach(r => (r.rotation.y += dt * sim.speed * sim.rate * 0.8));
  // explode
  const e = sim.explode;
  valveRing.position.y = e * 0.6; bowl.position.y = e * 1.15; capTop.position.y = e * 0.5;
  for (const gp of guardPanels){ gp.g.position.set(gp.x + gp.nx * e * 1.3, 0, gp.z + gp.nz * e * 1.3); }
  guardMat.opacity = 0.2 * (1 - e * 0.85);
  // inspection light: pulse with each bottle, red on NG
  const ph = mod((S - S_INSP) / P, 1);
  const ngNow = performance.now() < flashUntil;
  inspPanel.material.emissive.setHex(ngNow ? 0xff3344 : 0xffffff);
  inspPanel.material.emissiveIntensity = ngNow ? 2.2 : 0.55 + 0.6 * Math.exp(-ph * 9) * (sim.speed > 0.02 ? 1 : 0);
  towerLights[0].material.emissiveIntensity = sim.estop || sim.alarm ? 0.05 : 1.2;
  towerLights[1].material.emissiveIntensity = sim.alarm && !sim.estop ? (Math.sin(simT * 8) > 0 ? 1.6 : 0.1) : 0.05;
  towerLights[2].material.emissiveIntensity = sim.estop || ngNow ? (Math.sin(simT * 10) > 0 ? 1.8 : 0.2) : 0.05;
  tunnelGlow.material.emissiveIntensity = 0.5 + 0.7 * sim.speed;
  // reject pusher: extends while a defective bottle passes the reject point
  let push = 0;
  for (const n of sim.defects){ const s = S - n * P; if (s > S_REJ - 0.12 && s < S_REJ + 0.5) push = Math.max(push, Math.sin(Math.PI * clamp01((s - (S_REJ - 0.12)) / 0.62))); }
  pusher.scale.z = 0.08 + push * 0.42; pusher.position.z = -0.2 + push * 0.21;
}

// packs + robot
const PU = V(PACK_X0 + LP, PACK_Y, ZL);
function slotPos(j, out){ const k = mod(j, 36), layer = Math.floor(k / 9), idx = k % 9; return out.set(PAL.x + (idx % 3 - 1) * 0.38, 0.15 + layer * 0.335, PAL.z + (Math.floor(idx / 3) - 1) * 0.29); }
function cylOf(p){ return { a: Math.atan2(-(p.z - RB.z), p.x - RB.x), r: Math.hypot(p.x - RB.x, p.z - RB.z), y: p.y }; }
function lerpCyl(p, q, k, lift, out){
  const A = cylOf(p), Bq = cylOf(q); let da = mod(Bq.a - A.a + Math.PI, TAU) - Math.PI;
  const a = A.a + da * k, r = lerp(A.r, Bq.r, k), y = lerp(A.y, Bq.y, k) + Math.sin(Math.PI * k) * lift;
  return out.set(RB.x + Math.cos(a) * r, y, RB.z - Math.sin(a) * r);
}
const _t = new THREE.Vector3(), _sl = new THREE.Vector3(), _h1 = new THREE.Vector3(), _h2 = new THREE.Vector3();
function robotTarget(phi, j, out){
  slotPos(j, _sl);
  const puH = _h1.copy(PU).setY(PU.y + 0.45), slH = _h2.copy(_sl).setY(_sl.y + 0.45);
  if (phi < 0.12) return out.copy(PU).setY(PU.y + 0.4 * (1 - smooth(phi / 0.12)));
  if (phi < 0.2) return out.copy(PU).setY(PU.y + 0.45 * smooth((phi - 0.12) / 0.08));
  if (phi < 0.55) return lerpCyl(puH, slH, easeIO((phi - 0.2) / 0.35), 0.25, out);
  if (phi < 0.68) return out.copy(_sl).setY(_sl.y + 0.45 * (1 - smooth((phi - 0.55) / 0.13)));
  if (phi < 0.8) return out.copy(_sl).setY(_sl.y + 0.45 * smooth((phi - 0.68) / 0.12));
  const pr = _t.copy(PU).setY(PU.y + 0.4); return lerpCyl(slH, pr, easeIO((phi - 0.8) / 0.2), 0.2, out);
}
function setRobot(T, grip){
  const W = _p.copy(T).setY(T.y + PACK_H + TOOL);
  const dx = W.x - RB.x, dz = W.z - RB.z, r = Math.hypot(dx, dz), h = W.y - SH;
  robot.turret.rotation.y = Math.atan2(-dz, dx);
  const d = Math.min(Math.hypot(r, h), L1 + L2 - 0.01);
  const e = Math.acos(Math.max(-1, Math.min(1, (d * d - L1 * L1 - L2 * L2) / (2 * L1 * L2))));
  const a = Math.atan2(h, r) + Math.atan2(L2 * Math.sin(e), L1 + L2 * Math.cos(e));
  robot.upper.rotation.z = a; robot.fore.rotation.z = -e; robot.wrist.rotation.z = -Math.PI / 2 - (a - e);
  robot.fingers.forEach((f, i) => (f.position.z = (i ? 1 : -1) * (grip ? 0.145 : 0.19)));
}
const _rt = new THREE.Vector3();
function updatePacks(){
  const S = sim.S, made = Math.floor((S - S_END) / (12 * P));
  packPool.forEach(g => (g.visible = false));
  const st = palletState();
  const cyc = st.placed >= 0 ? Math.floor(st.placed / 36) : -1;
  let job = -1, jobPhi = 0;
  for (let j = Math.max(0, made - 50); j < made; j++){
    const u = (S - (S_END + 12 * P * (j + 1))) * 0.4;
    const g = packPool[mod(j, NPACK)];
    if (u < LP){ g.position.set(PACK_X0 + Math.max(u, -1.4), PACK_Y, ZL); g.visible = u > -1.2; continue; }
    const phi = (u - LP) / PACK_P;
    if (phi < 1){ job = j; jobPhi = phi; }
    if (phi < 0.12){ g.position.copy(PU); g.visible = true; }
    else if (phi < 0.68){ robotTarget(phi, j, g.position); g.visible = true; }
    else if (Math.floor(j / 36) === cyc){ slotPos(j, g.position); g.visible = true; }
  }
  if (job >= 0){ robotTarget(jobPhi, job, _rt); setRobot(_rt, jobPhi >= 0.1 && jobPhi < 0.7); }
}

/* ================= events / alerts ================= */
let flashUntil = 0;
const toastEl = document.getElementById('toast'); let toastTimer = 0;
function toast(msg, kind = '', ms = 3200){ toastEl.textContent = msg; toastEl.className = 'toast show ' + kind; clearTimeout(toastTimer); toastTimer = setTimeout(() => (toastEl.className = 'toast ' + kind), ms); }
let ngTag = null;
function checkEvents(prevS){
  for (const n of sim.defects){
    const s = sim.S - n * P, sp = prevS - n * P;
    if (sp < S_INSP && s >= S_INSP){ flashUntil = performance.now() + 1400; sim.lastNG = `#${serialOf(n)} · thiếu nắp`; toast(`Soi đèn NG · chai #${serialOf(n)} thiếu nắp → loại bỏ`, 'bad'); ngTag = { n, until: performance.now() + 2600 }; }
    if (sp < S_REJ && s >= S_REJ){ sim.rejects++; }
    if (s > S_END + 1) sim.defects.delete(n);
  }
}
function injectDefect(){
  const n = Math.floor((sim.S - S_CAP) / P) + 1;
  sim.defects.add(n); toast(`Đã gây lỗi: chai #${serialOf(n)} sẽ thiếu nắp`, 'warn');
  return n;
}
function setAlarm(on){
  sim.alarm = on;
  for (let i = 0; i < NV; i++) valveRods.setColorAt(i, new THREE.Color(on && i === 24 ? 0xff2d2d : 0xffffff));
  valveRods.material.emissive.setHex(0x000000);
  valveRods.instanceColor.needsUpdate = true;
  toast(on ? 'Van chiết #24 áp suất thấp · toàn tuyến giảm còn 60%' : 'Đã xử lý van #24 · sản lượng hồi phục', on ? 'warn' : 'ok', 3600);
  syncButtons();
}
function setEstop(on){
  sim.estop = on;
  toast(on ? 'DỪNG KHẨN · toàn tuyến dừng trong 0,6 giây' : 'Khởi động lại · về tốc độ định mức sau 2,5 giây', on ? 'bad' : 'ok', 3600);
  syncButtons();
}

/* ================= camera ================= */
function viewPose(v){ const [t, dist, az, el] = v; const a = az * Math.PI / 180, e = el * Math.PI / 180;
  return { t: t.clone(), p: V(t.x + Math.sin(a) * Math.cos(e) * dist, t.y + Math.sin(e) * dist, t.z + Math.cos(a) * Math.cos(e) * dist) }; }
const OVERVIEW = [V(-0.5, 0.5, 0.6), 39, 16, 35];
let fly = null;
function flyTo(v, dur = 1.6){ const pose = Array.isArray(v) ? viewPose(v) : v; fly = { t0: performance.now(), dur: dur * 1000, fp: camera.position.clone(), ft: controls.target.clone(), tp: pose.p, tt: pose.t }; }
{ const p0 = viewPose(OVERVIEW); camera.position.copy(p0.p); controls.target.copy(p0.t); }

/* ================= selection / follow ================= */
let selected = null, follow = null;
const panel = document.getElementById('panel');
function select(id, flyCam = true){
  selected = id; follow = null; syncButtons();
  if (id && flyCam) flyTo(MACH[id].view, 1.5);
  if (!id && flyCam) flyTo(OVERVIEW, 1.6);
  document.querySelectorAll('.tabs button').forEach(b => b.classList.toggle('on', b.dataset.id === (id || 'all')));
  renderPanel(true);
}
function startFollow(n){
  selected = null; follow = { n, t0: clockStr() , marks: {} };
  const p = bottlePos(n, new THREE.Vector3()); if (!p) return;
  flyTo({ p: p.clone().add(V(1.15, 0.9, 1.55)), t: p.clone().setY(p.y + 0.15) }, 1.0);
  syncButtons(); renderPanel(true);
}
function pickBottleNear(s){ return Math.round((sim.S - s) / P); }

/* ================= HUD ================= */
const tabsEl = document.getElementById('tabs');
const TABS = [['all', 'Tổng quan'], ['tanks', 'Xử lý nước'], ['blow', 'Thổi chai'], ['filler', 'Chiết rót & đóng nắp'], ['insp', 'Soi đèn & loại'], ['label', 'Dán nhãn'], ['wrap', 'Màng co'], ['robot', 'Xếp pallet'], ['store', 'Kho']];
for (const [id, name] of TABS){ const b = document.createElement('button'); b.textContent = name; b.dataset.id = id; b.onclick = () => { stopTour(); select(id === 'all' ? null : id); }; tabsEl.appendChild(b); }
tabsEl.firstChild.classList.add('on');
const labelsEl = document.getElementById('labels');
const tags = [];
for (const id of Object.keys(MACH)){
  const d = document.createElement('div'); d.className = 'tag'; d.textContent = MACH[id].name; d.onclick = () => { stopTour(); select(id); };
  labelsEl.appendChild(d); tags.push({ el: d, id, pos: MACH[id].anchor });
}
const partTags = [['Bồn chứa trên', () => V(FX, 2.45 + sim.explode * 1.15, FZ)], ['60 van chiết', () => V(FX - RF, 1.85 + sim.explode * 0.6, FZ)], ['18 đầu đóng nắp', () => V(CXc + 0.2, 2.05 + sim.explode * 0.5, CZc)], ['Mâm chai', () => V(FX + 0.5, 1.0, FZ + RF)]]
  .map(([t, f]) => { const d = document.createElement('div'); d.className = 'tag part'; d.textContent = t; labelsEl.appendChild(d); return { el: d, f }; });
const ngEl = document.createElement('div'); ngEl.className = 'tag ng'; ngEl.textContent = 'NG · thiếu nắp'; labelsEl.appendChild(ngEl);
const rejEl = document.createElement('div'); rejEl.className = 'tag ng'; rejEl.textContent = 'LOẠI'; labelsEl.appendChild(rejEl);
const _v = new THREE.Vector3();
function placeTag(el, p, show){
  if (!show){ el.style.opacity = 0; el.style.pointerEvents = 'none'; return; }
  _v.copy(p).project(camera);
  if (_v.z > 1 || Math.abs(_v.x) > 1.1 || Math.abs(_v.y) > 1.1){ el.style.opacity = 0; el.style.pointerEvents = 'none'; return; }
  el.style.left = ((_v.x + 1) / 2 * innerWidth) + 'px'; el.style.top = ((1 - _v.y) / 2 * innerHeight) + 'px';
  el.style.opacity = 1; el.style.pointerEvents = 'auto';
}
function updateTags(){
  const camD = camera.position.distanceTo(controls.target);
  for (const t of tags){ const d = camera.position.distanceTo(t.pos); placeTag(t.el, t.pos, !follow && (camD > 9 || t.id === selected) && d > 2.5); t.el.classList.toggle('sel', t.id === selected); }
  for (const t of partTags) placeTag(t.el, t.f(), sim.explode > 0.15);
  const now = performance.now();
  if (ngTag && now < ngTag.until){ const p = bottlePos(ngTag.n, _bp); placeTag(ngEl, p ? _p.copy(p).setY(p.y + 0.42) : V(0, -99, 0), !!p); } else placeTag(ngEl, null, false);
  let rej = false; for (const n of sim.defects){ const s = sim.S - n * P; if (s > S_REJ - 0.4 && s < S_REJ + 1.2) rej = true; }
  placeTag(rejEl, V(X_REJ, 1.35, ZL - 0.3), rej);
}
const chipFor = id => {
  if (sim.estop) return ['Dừng', 'bad'];
  if (sim.paused) return ['Tạm dừng', 'idle'];
  if (sim.alarm && id === 'filler') return ['Báo động', 'bad'];
  if (sim.alarm) return ['Giảm tốc', 'warn'];
  return ['Vận hành', ''];
};
let lastPanel = 0;
function renderPanel(force){
  const now = performance.now(); if (!force && now - lastPanel < 220) return; lastPanel = now;
  let h = '';
  if (follow){
    const p = bottlePos(follow.n, _bp), s = sim.S - follow.n * P, def = sim.defects.has(follow.n);
    const cur = STATIONS.reduce((c, st, i) => (s >= st.s ? i : c), 0);
    STATIONS.forEach((st, i) => { if (s >= st.s && !follow.marks[i]) follow.marks[i] = clockStr(); });
    const lvl = clamp01((s - S_FILL0) / (S_FILL1 - S_FILL0)) * 100;
    const rejected = def && s >= S_REJ;
    h = `<div class="p-eye">Truy vết từng chai</div><div class="p-head"><div class="p-title">#${serialOf(follow.n)}</div><span class="chip ${rejected ? 'bad' : ''}">${rejected ? 'Đã loại' : s >= S_END ? 'Đã đóng lốc' : 'Đang sản xuất'}</span></div>
      <div class="rows"><div class="row"><span>Công đoạn hiện tại</span><b class="blue">${STATIONS[cur].name}</b></div>
      <div class="row"><span>Mức nước</span><b>${fmt1(lvl)}%</b></div>
      <div class="row"><span>Nắp</span><b class="${def ? 'bad' : ''}">${def ? 'Không có' : s >= S_CAP ? 'Đã siết · 1,6 N·m' : 'Chưa'}</b></div>
      <div class="row"><span>Lốc / pallet</span><b>${s >= S_END ? `L${Math.floor((sim.S - S_END) / (12 * P)) + 15000}` : '—'}</b></div></div><div class="tl">` +
      STATIONS.map((st, i) => { const ng = rejected && st.k === 'insp'; const cls = ng ? 'ng' : i < cur || (i === cur && s >= S_END) ? 'done' : i === cur ? 'cur' : '';
        const skip = rejected && i > STATIONS.findIndex(x => x.k === 'insp');
        return `<div class="${skip ? '' : cls}"><i></i>${st.name}${ng ? ' · NG' : ''}<time>${!skip && follow.marks[i] ? follow.marks[i] : ''}</time></div>`; }).join('') + `</div>`;
  } else if (selected){
    const m = MACH[selected], [txt, cls] = chipFor(selected);
    h = `<div class="p-eye">Thiết bị</div><div class="p-head"><div class="p-title">${m.name}</div><span class="chip ${cls}">${txt}</span></div><div class="rows">` +
      m.rows().map(([k, v, c]) => `<div class="row"><span>${k}</span><b class="${c || ''}">${v}</b></div>`).join('') + `</div>`;
  } else {
    const [txt, cls] = chipFor('');
    h = `<div class="p-eye">Xưởng</div><div class="p-head"><div class="p-title">Tổng quan xưởng chiết</div><span class="chip ${cls}">${txt}</span></div><div class="rows">
      <div class="row"><span>Công suất định mức</span><b>24.000 chai/giờ</b></div>
      <div class="row"><span>Nhịp</span><b>${sim.speed < 0.05 ? '—' : fmt2(0.15 / sim.speed) + ' s/chai'}</b></div>
      <div class="row"><span>Tốc độ dây chuyền</span><b class="blue">${fmt2(VNOM * sim.speed)} m/s</b></div>
      <div class="row"><span>Loại chai</span><b>1,5 L PET</b></div>
      <div class="row"><span>Đang trên dây chuyền</span><b>${fmt(Math.round(S_END / P))} chai</b></div></div>
      <p class="p-hint">Bấm vào một máy để xem thông số, hoặc bấm thẳng vào một chai để truy vết.</p>`;
  }
  panel.innerHTML = h;
}
const kOee = document.getElementById('kOee'), kRate = document.getElementById('kRate'), kToday = document.getElementById('kToday'), kRej = document.getElementById('kRej');
const pill = document.getElementById('pill'), pillTxt = document.getElementById('pillTxt'), clockEl = document.getElementById('clock');
let oeeShown = 89.2;
const clockStr = () => { const d = new Date(); return d.toTimeString().slice(0, 8); };
function updateHUD(){
  const target = (89.4 + Math.sin(simT * 0.21) * 0.4) * (sim.estop ? 0.93 : 1) - (1 - sim.speed) * 2.2;
  oeeShown += (target - oeeShown) * 0.02;
  kOee.textContent = fmt1(oeeShown) + '%';
  kRate.textContent = fmt(rateNow());
  kToday.textContent = fmt(186420 + Math.floor((sim.S - S0) / P));
  kRej.textContent = fmt(sim.rejects);
  const st = sim.estop ? ['Dừng khẩn', 'bad'] : sim.paused ? ['Tạm dừng', 'warn'] : sim.alarm ? ['Giảm tốc 60%', 'warn'] : ['Đang chạy', ''];
  pillTxt.textContent = st[0]; pill.className = 'pill ' + st[1];
  clockEl.textContent = clockStr();
}

/* ================= minimap ================= */
const mini = document.getElementById('mini'), mctx = mini.getContext('2d');
const MW = mini.width, MH = mini.height, MX0 = HALL.x0, MX1 = HALL.x1, MZ0 = HALL.z0, MZ1 = HALL.z1;
const mx = x => (x - MX0) / (MX1 - MX0) * (MW - 20) + 10, mz = z => (z - MZ0) / (MZ1 - MZ0) * (MH - 20) + 10;
function drawMini(){
  mctx.clearRect(0, 0, MW, MH);
  mctx.fillStyle = '#eef1f5'; mctx.fillRect(0, 0, MW, MH);
  mctx.strokeStyle = '#c4cbd4'; mctx.lineWidth = 2; mctx.strokeRect(mx(MX0), mz(MZ0), mx(MX1) - mx(MX0), mz(MZ1) - mz(MZ0));
  mctx.fillStyle = 'rgba(70,176,111,.35)'; mctx.fillRect(mx(MX0), mz(6.55), mx(MX1) - mx(MX0), mz(8.25) - mz(6.55));
  for (const id of Object.keys(MACH)){ const f = MACH[id].foot; mctx.fillStyle = id === selected ? '#2563eb' : '#ffffff'; mctx.strokeStyle = '#9aa5b3'; mctx.lineWidth = 1.2;
    mctx.beginPath(); mctx.roundRect(mx(f[0]), mz(f[1]), mx(f[2]) - mx(f[0]), mz(f[3]) - mz(f[1]), 3); mctx.fill(); mctx.stroke(); }
  mctx.strokeStyle = '#2f6fdf'; mctx.lineWidth = 2; mctx.beginPath();
  for (let s = 0; s <= LPATH; s += 0.3){ path.at(s, _o); s === 0 ? mctx.moveTo(mx(_o.x), mz(_o.z)) : mctx.lineTo(mx(_o.x), mz(_o.z)); }
  mctx.lineTo(mx(PACK_X0 + LP), mz(ZL)); mctx.stroke();
  if (follow){ const p = bottlePos(follow.n, _bp); if (p){ mctx.fillStyle = '#ff6a1a'; mctx.beginPath(); mctx.arc(mx(p.x), mz(p.z), 5, 0, TAU); mctx.fill(); } }
  const t = controls.target, c = camera.position;
  mctx.fillStyle = 'rgba(37,99,235,.18)'; mctx.strokeStyle = '#2563eb'; mctx.lineWidth = 1.5;
  const ang = Math.atan2(t.z - c.z, t.x - c.x);
  mctx.beginPath(); mctx.moveTo(mx(t.x), mz(t.z));
  mctx.arc(mx(t.x), mz(t.z), 22, ang + Math.PI - 0.5, ang + Math.PI + 0.5); mctx.closePath(); mctx.fill(); mctx.stroke();
  mctx.fillStyle = '#2563eb'; mctx.beginPath(); mctx.arc(mx(t.x), mz(t.z), 4, 0, TAU); mctx.fill();
}
document.getElementById('miniWrap').addEventListener('click', e => {
  const r = mini.getBoundingClientRect(); const px = (e.clientX - r.left) / r.width * MW, pz = (e.clientY - r.top) / r.height * MH;
  const x = (px - 10) / (MW - 20) * (MX1 - MX0) + MX0, z = (pz - 10) / (MH - 20) * (MZ1 - MZ0) + MZ0;
  stopTour(); follow = null; selected = null; syncButtons();
  flyTo([V(x, 0.8, z), 11, 18, 32], 1.3); renderPanel(true);
});

/* ================= controls wiring ================= */
const $ = id => document.getElementById(id);
function syncButtons(){
  $('bFollow').classList.toggle('on', !!follow);
  $('bXray').classList.toggle('on', sim.xray);
  $('bAlarm').classList.toggle('on', sim.alarm);
  $('bStop').classList.toggle('on', sim.estop);
  $('bStop').textContent = sim.estop ? 'Khởi động lại' : 'Dừng khẩn';
  $('bPause').classList.toggle('on', sim.paused);
  document.querySelectorAll('[data-rate]').forEach(b => b.classList.toggle('on', +b.dataset.rate === sim.rate));
  $('bTour').classList.toggle('on', !!tour);
  $('bTour').querySelector('span').textContent = tour ? 'Dừng tour' : 'Chạy tour';
}
document.querySelectorAll('[data-rate]').forEach(b => b.onclick = () => { sim.rate = +b.dataset.rate; syncButtons(); });
$('bPause').onclick = () => { sim.paused = !sim.paused; syncButtons(); };
$('bFollow').onclick = () => { stopTour(); if (follow){ follow = null; select(null); } else startFollow(pickBottleNear(S_FILL0 + 0.6)); };
$('bXray').onclick = () => { sim.xray = !sim.xray; setXray(sim.xray); syncButtons(); };
$('explode').oninput = e => { stopTour(); sim.explodeTarget = +e.target.value; if (selected !== 'filler') select('filler'); };
$('bDefect').onclick = () => { stopTour(); const n = injectDefect(); if (selected !== 'insp') select('insp'); };
$('bAlarm').onclick = () => { stopTour(); setAlarm(!sim.alarm); };
$('bStop').onclick = () => { stopTour(); setEstop(!sim.estop); };
$('bReset').onclick = () => { stopTour(); resetAll(); };
function setXray(on){ housingMats.forEach(m => { m.transparent = on; m.opacity = on ? 0.18 : 1; m.depthWrite = !on; m.needsUpdate = true; }); }
function resetAll(){ sim.estop = false; sim.alarm && setAlarm(false); sim.paused = false; sim.rate = 1; sim.explodeTarget = 0; $('explode').value = 0; sim.xray = false; setXray(false); follow = null; select(null); syncButtons(); }

// picking
const ray = new THREE.Raycaster(), ndc = new THREE.Vector2();
let downAt = null;
canvas.addEventListener('pointerdown', e => { downAt = [e.clientX, e.clientY]; });
canvas.addEventListener('pointerup', e => {
  if (!downAt || Math.hypot(e.clientX - downAt[0], e.clientY - downAt[1]) > 5) return;
  ndc.set(e.clientX / innerWidth * 2 - 1, -(e.clientY / innerHeight) * 2 + 1);
  ray.setFromCamera(ndc, camera);
  bodies.computeBoundingSphere();
  const hits = ray.intersectObjects([bodies, ...pickRoots], true);
  if (!hits.length) return;
  const h = hits[0];
  stopTour();
  if (h.object === bodies && h.instanceId !== undefined){
    const nMax = Math.floor(sim.S / P), n = nMax - mod(nMax - h.instanceId, NB); startFollow(n); return;
  }
  let o = h.object; while (o && !o.userData.mid) o = o.parent;
  if (o) select(o.userData.mid);
});
canvas.addEventListener('pointermove', e => {
  if (e.buttons) return;
  ndc.set(e.clientX / innerWidth * 2 - 1, -(e.clientY / innerHeight) * 2 + 1);
  ray.setFromCamera(ndc, camera);
  const h = ray.intersectObjects(pickRoots, true)[0];
  canvas.style.cursor = h ? 'pointer' : 'grab';
});
controls.addEventListener('start', () => { fly = null; });
addEventListener('keydown', e => {
  if (e.target.tagName === 'INPUT') return;
  if (e.key === 't' || e.key === 'T') { tour ? stopTour() : startTour(); }
  if (e.key === 'Escape') { stopTour(); }
  if (e.code === 'Space'){ e.preventDefault(); sim.paused = !sim.paused; syncButtons(); }
});

/* ================= tour: 9 chapters ================= */
const capNum = $('capNum'), capTitle = $('capTitle'), capSub = $('capSub'), capBar = $('capBar');
let tour = null;
const CH = [
  { d: 8, title: 'Nhà máy này là một trang web.', sub: 'Claude Code × Three.js · bản sao số dây chuyền chiết rót nước 1,5L',
    enter(){ resetAll(); flyTo([V(-1.5, 0.5, 0.2), 34, 8, 34], 2.4); controls.autoRotate = true; } },
  { d: 8, title: 'Bấm máy nào, xem máy đó.', sub: 'Chọn máy chiết rót 3 trong 1 · thông số sản xuất cập nhật theo thời gian thực',
    enter(){ controls.autoRotate = false; select('filler'); }, at: [[4.2, () => select('insp')]] },
  { d: 9, title: 'Tách máy chiết rót thành từng lớp.', sub: 'Kéo thanh trượt: bồn chứa, 60 van chiết, 18 đầu đóng nắp hiện ra rõ ràng',
    enter(){ select('filler', false); flyTo([V(-8.9, 1.8, 1.6), 8.6, 18, 18], 1.4); },
    update(t){ const e = t < 1.2 ? 0 : t < 3.6 ? easeIO((t - 1.2) / 2.4) : t < 6.6 ? 1 : 1 - easeIO((t - 6.6) / 2.2); sim.explodeTarget = e; $('explode').value = e; } },
  { d: 11, title: 'Bấm một chai, camera bám theo.', sub: 'Truy vết từng chai: thổi, chiết, đóng nắp, soi đèn, dán nhãn · từng mốc sáng lên',
    enter(){ sim.explodeTarget = 0; $('explode').value = 0; startFollow(pickBottleNear(S_FILL0 + 1.4)); } },
  { d: 10, title: 'Thiếu nắp, loại ngay tại chỗ.', sub: 'Gây lỗi thật: camera soi đèn báo NG, cần đẩy gạt chai ra khỏi dây chuyền',
    enter(){ follow = null; select('insp', false); flyTo([V(X_INSP + 0.3, 1.0, ZL + 0.15), 3.6, 34, 24], 1.3); }, at: [[0.6, () => injectDefect()]] },
  { d: 10, title: 'Một van báo động, cả dây chuyền giảm tốc.', sub: 'Van chiết #24 lỗi: tốc độ toàn tuyến hạ còn 60%, sản lượng và OEE đổi theo',
    enter(){ select('filler', false); flyTo([V(-8.8, 1.5, 1.5), 7.6, 22, 30], 1.4); }, at: [[1.2, () => setAlarm(true)], [7.6, () => setAlarm(false)]] },
  { d: 9, title: 'Một nút dừng khẩn, cả tuyến đứng yên.', sub: 'Dừng trong 0,6 giây · khởi động lại về đủ tốc độ sau 2,5 giây',
    enter(){ select(null, false); flyTo([V(-2.5, 0.6, 1.2), 26, 14, 30], 1.6); }, at: [[1.6, () => setEstop(true)], [5.6, () => setEstop(false)]] },
  { d: 9, title: 'Robot xếp pallet theo nhịp.', sub: 'Mỗi lốc 12 chai · 9 lốc một lớp · 4 lớp một pallet · bấm bản đồ nhỏ để định vị',
    enter(){ select('robot'); } },
  { d: 8, title: 'Từ một câu yêu cầu, tới cả một nhà máy.', sub: 'Mô tả yêu cầu → Claude Code viết và sửa → Three.js mô phỏng',
    enter(){ select(null, false); flyTo([V(-1.5, 0.5, 0.2), 40, -8, 38], 3.2); controls.autoRotate = true; } }
];
function setCaption(i){
  if (i < 0){ capNum.textContent = 'TƯƠNG TÁC'; capTitle.textContent = 'Nhà máy này là một trang web.'; capSub.textContent = 'Bấm vào máy hoặc một chai nước · kéo để xoay · cuộn để phóng to · phím T để chạy tour'; capBar.style.width = '0'; return; }
  capNum.textContent = `${String(i + 1).padStart(2, '0')} / ${String(CH.length).padStart(2, '0')}`; capTitle.textContent = CH[i].title; capSub.textContent = CH[i].sub;
}
function startTour(){ tour = { i: -1, t: 0 }; nextChapter(); syncButtons(); }
function stopTour(){ if (!tour) return; tour = null; controls.autoRotate = false; setCaption(-1); syncButtons(); }
function nextChapter(){
  tour.i++; tour.t = 0; tour.fired = new Set();
  if (tour.i >= CH.length){ tour = null; controls.autoRotate = false; setCaption(-1); syncButtons(); return; }
  setCaption(tour.i); CH[tour.i].enter();
}
function updateTour(dt){
  if (!tour) return;
  tour.t += dt; const c = CH[tour.i];
  (c.at || []).forEach(([tt, f], k) => { if (tour.t >= tt && !tour.fired.has(k)){ tour.fired.add(k); f(); } });
  if (c.update) c.update(tour.t);
  capBar.style.width = (tour.t / c.d * 100) + '%';
  if (tour.t >= c.d) nextChapter();
}

/* ================= post-processing ================= */
const rt = new THREE.WebGLRenderTarget(innerWidth * DPR, innerHeight * DPR, { type: THREE.HalfFloatType, samples: 4 });
const composer = new EffectComposer(renderer, rt);
composer.addPass(new RenderPass(scene, camera));
let gtao = null;
try {
  gtao = new GTAOPass(scene, camera, innerWidth, innerHeight);
  gtao.output = GTAOPass.OUTPUT.Default; gtao.blendIntensity = 0.85;
  gtao.updateGtaoMaterial({ radius: 0.45, distanceExponent: 1.4, thickness: 1.0, scale: 1.0, samples: 12, distanceFallOff: 1, screenSpaceRadius: false });
  gtao.updatePdMaterial({ lumaPhi: 10, depthPhi: 2, normalPhi: 3, radius: 5, radiusExponent: 1, rings: 2, samples: 12 });
  composer.addPass(gtao);
} catch (e) { console.warn('GTAO unavailable', e); }
composer.addPass(new OutputPass());
function resize(){
  const w = innerWidth, h = innerHeight;
  renderer.setSize(w, h, false); composer.setPixelRatio(DPR); composer.setSize(w, h);
  camera.aspect = w / h; camera.updateProjectionMatrix();
}
addEventListener('resize', resize); resize();

/* ================= main loop ================= */
let last = performance.now();
function frame(now){
  const dt = Math.min(0.1, (now - last) / 1000); last = now;
  const freeze = window.__freezeT;
  const dts = sim.paused ? 0 : dt * sim.rate;
  simT += dts;
  // speed dynamics: e-stop 0.6 s, restart ramp 2.5 s
  const target = sim.estop ? 0 : sim.alarm ? 0.6 : 1;
  if (sim.speed > target) sim.speed = Math.max(target, sim.speed - dts / (sim.estop ? 0.6 : 1.2));
  else sim.speed = Math.min(target, sim.speed + dts / 2.5);
  const prevS = sim.S; sim.S += VNOM * sim.speed * dts;
  checkEvents(prevS);
  sim.explode += (sim.explodeTarget - sim.explode) * Math.min(1, dt * 6);
  updateTour(dt);

  updateBottles(); updateMachines(dts); updatePacks();
  // workers + forklift (own clock, freeze on e-stop not needed)
  for (const w of walkers){
    const s = mod(simT * w.speed + w.off * 5, w.L); const sg = w.seg.find(q => s < q.s0 + q.l) || w.seg[0]; const k = (s - sg.s0) / sg.l;
    w.p.g.position.set(lerp(sg.a[0], sg.b[0], k), 0, lerp(sg.a[1], sg.b[1], k)); w.p.g.rotation.y = Math.atan2(-(sg.b[1] - sg.a[1]), sg.b[0] - sg.a[0]);
    const sw = Math.sin(simT * 7 * w.speed) * 0.5; w.p.legs[0].rotation.z = sw; w.p.legs[1].rotation.z = -sw; w.p.arms[0].rotation.z = -sw * 0.6; w.p.arms[1].rotation.z = sw * 0.6;
  }
  standers.forEach((p, i) => { p.g.rotation.y += Math.sin(simT * 0.7 + i) * 0.002; });
  { const T = 16, u = mod(simT, T) / T, f = forklift.g;
    const zA = 2.4, zB = -2.0, x = 16.6;
    let z, yaw, lift;
    if (u < 0.4){ z = lerp(zA, zB, easeIO(u / 0.4)); yaw = Math.PI / 2; lift = 0.3; }
    else if (u < 0.5){ z = zB; yaw = Math.PI / 2 + Math.PI * easeIO((u - 0.4) / 0.1); lift = 0.3; }
    else if (u < 0.9){ z = lerp(zB, zA, easeIO((u - 0.5) / 0.4)); yaw = -Math.PI / 2; lift = 0.3; }
    else { z = zA; yaw = -Math.PI / 2 + Math.PI * easeIO((u - 0.9) / 0.1); lift = 0.3; }
    f.position.set(x, 0, z); f.rotation.y = yaw; forklift.carriage.position.y = 0.12 + lift; forklift.load.visible = u < 0.45; }

  // camera
  if (fly){
    const k = easeIO((now - fly.t0) / fly.dur);
    camera.position.lerpVectors(fly.fp, fly.tp, k); controls.target.lerpVectors(fly.ft, fly.tt, k);
    if (k >= 1) fly = null;
  }
  if (follow){
    const p = bottlePos(follow.n, _bp);
    if (!p || p.s >= S_END - 0.05 || (sim.defects.has(follow.n) && p.s > S_REJ + 1.2)){
      const n = follow.n; follow = null; syncButtons();
      if (!tour){ toast(`Chai #${serialOf(n)} đã ${sim.defects.has(n) ? 'bị loại' : 'vào máy màng co'}`, 'ok'); select('wrap'); }
    } else {
      _p.set(p.x, p.y + 0.15, p.z);
      if (fly){ fly.tt.copy(_p); fly.tp.copy(_p).add(V(1.15, 0.9, 1.55)); }
      else { const d = _p.clone().sub(controls.target); camera.position.add(d); controls.target.copy(_p); }
    }
  }
  controls.update();
  updateTags(); renderPanel(false); updateHUD(); drawMini();
  composer.render();
  requestAnimationFrame(frame);
}
window.__dbg = { sim, startTour, next: () => nextChapter(), get tour(){ return tour; }, CH, select, flyTo, V };
window.__sceneOK = true;
setCaption(-1); renderPanel(true); syncButtons();
if (location.hash === '#tour') startTour();
requestAnimationFrame(frame);
</script>
</body>
</html>

Bộ prompt nhà máy nước

Prompt dựng nhà máy từ đầu, 8 câu lệnh chỉnh sửa (đổi sản phẩm, bản dọc 9:16, thêm trạm, thêm sự cố...), kịch bản tour 9 chương kèm lời lồng tiếng gợi ý.

nha-may-nuoc/prompt/01-prompt-dung-nha-may.txt
PROMPT DỰNG BẢN SAO SỐ (DIGITAL TWIN) DÂY CHUYỀN CHIẾT RÓT NƯỚC
Cường Mê AI · Dán nguyên văn vào Claude. Đổi các chỗ trong [ngoặc vuông] nếu muốn.
--------------------------------------------------------------------

Build a single-file web app (HTML, CSS, JS) that is an interactive 3D digital twin of a [1.5 L bottled-water production line] inside a factory hall. Use Three.js from a CDN (full URLs, no import map dependency), OrbitControls, MeshStandardMaterial, one sun with soft shadows plus a hemisphere light, ACES tone mapping and a GTAO ambient-occlusion pass. Fill the whole window, 16:9 layout, no scrollbars, autoplay. All UI text in Vietnamese.

THE LINE (left to right, real scale in metres):
[water treatment tanks] -> [blow molder] -> air conveyor -> [3-in-1 rotary filler with exactly 60 filling valves + capper with 18 capping heads + cap sorter] -> [light inspection station with a red reject pusher and reject table] -> [labeler + shrink sleeve tunnel] -> [shrink wrapper making packs of 12] -> roller conveyor -> [orange 6-axis palletizing robot, 9 packs per layer, 4 layers per pallet] -> [finished-goods racking + forklift].
Also: control room on a mezzanine with stairs, a yellow crossover stair over the conveyor, electrical cabinets, workers in blue coveralls and white hard hats, green walkway and yellow floor markings.

SIMULATION:
- Bottles are instanced and follow one continuous path (straight lines + arcs around the filler and capper). Everything is driven by a single "line clock" so speed changes affect the whole line.
- Filler valves rotate with the bottles and lower while filling; water level rises in each bottle. Caps appear at the capper, labels at the labeler, bottles become packs at the wrapper, the robot picks each pack and stacks it on the pallet in sync.

INTERACTION:
- Click a machine (or a top tab) -> camera flies to it and a side panel shows live parameters.
- Click a bottle -> camera follows it; the panel shows a timeline of every station it passes with timestamps.
- "Tách lớp" slider -> exploded view of the filler (tank, 60-valve ring, 18 capping heads separate vertically, glass guards move outward).
- "Gây thiếu nắp" -> next bottle has no cap; inspection flashes red "NG", the pusher rejects it onto the reject table.
- "Lỗi van chiết" -> valve #24 turns red, whole line slows to 60%.
- "Dừng khẩn" -> line stops within 0.6 s; restart ramps back to full speed in 2.5 s.
- Minimap (click to fly there), pause, 1x/2x/4x speed, x-ray toggle, reset.

HUD: top bar with brand + tabs + running status + clock; KPI cards (OEE, real output in bottles/hour, today's count, rejects); device panel on the right; dark caption box with orange left border; control bar at the bottom.

TOUR: a "Chạy tour" button (and key T) that plays 9 chapters (~80 s) with captions: overview, click a machine, exploded view, follow a bottle, missing-cap reject, valve alarm slowdown, emergency stop, palletizing robot, closing wide shot.
nha-may-nuoc/prompt/02-lenh-chinh-sua.txt
CÂU LỆNH CHỈNH SỬA — Dán từng câu sau khi đã có mô hình
--------------------------------------------------------------------

[Đổi sản phẩm]
Đổi dây chuyền thành [sữa hộp giấy / bia lon / nước ngọt chai thủy tinh]: thay hình dáng sản phẩm, thay máy chiết bằng máy phù hợp, giữ nguyên toàn bộ tương tác.

[Đổi tên, thương hiệu]
Đổi tên nhà máy thành "[tên của bạn]", đổi màu chính sang [màu], đổi logo thành chữ cái đầu của tên.

[Bản dọc cho TikTok]
Làm thêm bản dọc 9:16 (1080×1920): xếp lại giao diện cho khung dọc, phụ đề to hơn, bảng thông số thu gọn, tour giữ nguyên 9 chương.

[Thêm trạm]
Thêm một trạm [in date bằng laser] giữa máy dán nhãn và máy màng co, có thông số riêng và hiện trong truy vết chai.

[Thêm sự cố]
Thêm nút "Kẹt chai ở băng tải": chai dồn ứ trước máy dán nhãn, cảm biến báo vàng, dây chuyền tự giảm tốc rồi hồi phục sau khi xử lý.

[Đổi số liệu]
Đổi công suất định mức thành [36.000] chai/giờ, OEE quanh [92%], thêm chỉ số tiêu thụ điện (kWh) vào bảng tổng quan.

[Máy yếu, chạy giật]
Thêm nút "Chất lượng thấp": tắt GTAO, giảm shadow map xuống 1024, giới hạn độ phân giải 1×.

[Phụ đề tour]
Viết lại phụ đề 9 chương theo giọng [hài hước / chuyên gia / kể chuyện], mỗi câu tiêu đề không quá 10 chữ.
nha-may-nuoc/prompt/03-kich-ban-tour-9-chuong.txt
KỊCH BẢN TOUR 9 CHƯƠNG (khoảng 82 giây) — dùng để đọc lồng tiếng hoặc làm phụ đề
--------------------------------------------------------------------
Mốc      Chương  Tiêu đề trên màn hình                          Chuyện gì xảy ra
0:00     01      Nhà máy này là một trang web.                  Toàn cảnh xưởng, camera xoay chậm.
0:08     02      Bấm máy nào, xem máy đó.                       Bay tới máy chiết rót, rồi trạm soi đèn; bảng thông số đổi theo.
0:16     03      Tách máy chiết rót thành từng lớp.             Bồn chứa, vòng 60 van, 18 đầu đóng nắp tách ra rồi ghép lại.
0:25     04      Bấm một chai, camera bám theo.                 Camera bám 1 chai từ máy chiết tới máy dán nhãn, từng mốc sáng lên.
0:36     05      Thiếu nắp, loại ngay tại chỗ.                  Chai thiếu nắp qua soi đèn: đèn đỏ, NG, cần đẩy gạt ra bàn loại.
0:46     06      Một van báo động, cả dây chuyền giảm tốc.      Van #24 đỏ, tốc độ còn 60%, sản lượng tụt; sau 6 giây hồi phục.
0:56     07      Một nút dừng khẩn, cả tuyến đứng yên.          Dừng trong 0,6 giây; khởi động lại, 2,5 giây về đủ tốc độ.
1:05     08      Robot xếp pallet theo nhịp.                    Robot gắp từng lốc 12 chai, xếp 9 lốc một lớp, 4 lớp một pallet.
1:14     09      Từ một câu yêu cầu, tới cả một nhà máy.        Camera kéo ra toàn cảnh, kết thúc ở 1:22.

GỢI Ý LỒNG TIẾNG (giọng Cường Mê AI, chỉnh lại theo ý anh em):
01: "Anh em nhìn kỹ nha, cả cái nhà máy này không phải phần mềm 3D gì hết, nó là một trang web."
02: "Bấm vô máy nào là bay tới máy đó, thông số chạy theo thời gian thực luôn."
03: "Muốn xem bên trong máy chiết? Kéo một cái là nó tách ra từng lớp."
04: "Bấm vô một chai, camera bám theo nó đi hết dây chuyền."
05: "Cố tình làm một chai thiếu nắp, coi nè, soi đèn bắt được, gạt ra liền."
06: "Một cái van báo lỗi là cả dây chuyền tự giảm tốc."
07: "Bấm dừng khẩn, chưa tới một giây là đứng hết."
08: "Cuối dây chuyền, robot xếp pallet đúng nhịp."
09: "Và tất cả bắt đầu từ một đoạn mô tả mình gõ cho Claude."
Khoá học AI Level Up

Học AI cùng Cường Mê AI

Học AI cho việc thật, không cần biết code.

  • 8 LevelTừ nền tảng đến kiếm tiền
  • ~100 bàiVideo thực chiến
  • 0 dòng codeKhông cần biết lập trình
Đăng ký học AI ngay
Nguồn tham khảo 5 nguồn
  1. Three.js: Tài liệu chính thức
  2. Three.js: Ví dụ hiệu ứng GTAO (ambient occlusion)
  3. jsDelivr: CDN phân phối thư viện Three.js
  4. OBS Studio: Phần mềm quay màn hình miễn phí
  5. Wikipedia: Digital twin (bản sao số)
Đọc tiếp
Tìm hiểu về Cường Đăng ký học AI ngay