diff --git a/zlt-business/device-center/src/main/resources/doc/waypoints.json b/zlt-business/device-center/src/main/resources/doc/waypoints.json new file mode 100644 index 00000000..98949bf8 --- /dev/null +++ b/zlt-business/device-center/src/main/resources/doc/waypoints.json @@ -0,0 +1,1148 @@ +{ + "routeId": "c928a113c4c2489883c41a038f0c7959", + "routeName": "Manual Route 2026/4/12 1:1:58", + "deviceSn": "SHIP-V1-00001", + "deviceName": "Koi Fish Agent", + "scenicId": 1, + "waypointCount": 75, + "totalDistance": 1157, + "totalDuration": 5785, + "cruiseSpeed": 0.2, + "loopEnabled": false, + "loopCount": 1, + "returnMode": "origin", + "safeDistance": 5, + "startPoint": "121.93510832728818,30.89157801991674", + "endPoint": "121.9281979067755,30.893500907105462", + "status": 1, + "statusDesc": "Local Draft", + "waypoints": [ + { + "waypointId": "ef51a516d3dd4d7fb0b9e9e0fe1cbdcc", + "waypointIndex": 0, + "longitude": 121.93510832728818, + "latitude": 30.89157801991674, + "altitude": 0.01, + "speed": 2, + "stayDuration": 0, + "headingAngle": 0, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "起点", + "actions": null, + "remark": null + }, + { + "waypointId": "fc88f8a0d01d4f24966e3220cbd65408", + "waypointIndex": 1, + "longitude": 121.93516932109242, + "latitude": 30.891585909152404, + "altitude": -0.01, + "speed": 2, + "stayDuration": 0, + "headingAngle": 83, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点1", + "actions": null, + "remark": null + }, + { + "waypointId": "b1ca78cc6de44f6cb3dcfa9d786ff8b3", + "waypointIndex": 2, + "longitude": 121.93525933279754, + "latitude": 30.89158876745163, + "altitude": 0.01, + "speed": 2, + "stayDuration": 0, + "headingAngle": 88, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点2", + "actions": null, + "remark": null + }, + { + "waypointId": "10b789a1c8584008b59f40d49ce5d5c4", + "waypointIndex": 3, + "longitude": 121.93534714800184, + "latitude": 30.891598731238542, + "altitude": 0, + "speed": 2, + "stayDuration": 0, + "headingAngle": 84, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点3", + "actions": null, + "remark": null + }, + { + "waypointId": "130e69c1e54e4b159569fe837196714c", + "waypointIndex": 4, + "longitude": 121.93535154442012, + "latitude": 30.89167736794725, + "altitude": 0.01, + "speed": 2, + "stayDuration": 0, + "headingAngle": 3, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点4", + "actions": null, + "remark": null + }, + { + "waypointId": "c5577eec59354907b009273176d6201e", + "waypointIndex": 5, + "longitude": 121.93536332307296, + "latitude": 30.891735723213305, + "altitude": 0, + "speed": 2, + "stayDuration": 0, + "headingAngle": 11, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点5", + "actions": null, + "remark": null + }, + { + "waypointId": "f179017a9f8c454287cb2e014243331e", + "waypointIndex": 6, + "longitude": 121.9353851925466, + "latitude": 30.89180827910997, + "altitude": 0, + "speed": 2, + "stayDuration": 0, + "headingAngle": 17, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点6", + "actions": null, + "remark": null + }, + { + "waypointId": "14f76cadba7440668d1bfed631979347", + "waypointIndex": 7, + "longitude": 121.935420967654, + "latitude": 30.891889203886183, + "altitude": -0.01, + "speed": 2, + "stayDuration": 0, + "headingAngle": 24, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点7", + "actions": null, + "remark": null + }, + { + "waypointId": "b87fb75746e44b519fae55025c8e996c", + "waypointIndex": 8, + "longitude": 121.93545536728114, + "latitude": 30.89199780205067, + "altitude": 0.02, + "speed": 2, + "stayDuration": 0, + "headingAngle": 18, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点8", + "actions": null, + "remark": null + }, + { + "waypointId": "d68862afe6bd4d1aa348a1bc02141889", + "waypointIndex": 9, + "longitude": 121.93546735183303, + "latitude": 30.89209628267529, + "altitude": -0.02, + "speed": 2, + "stayDuration": 0, + "headingAngle": 7, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点9", + "actions": null, + "remark": null + }, + { + "waypointId": "7443801fdec54ef18a31433065f12601", + "waypointIndex": 10, + "longitude": 121.93547335666307, + "latitude": 30.892207811363157, + "altitude": 0.02, + "speed": 2, + "stayDuration": 0, + "headingAngle": 3, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点10", + "actions": null, + "remark": null + }, + { + "waypointId": "b3daddfbe6ac4e1082dfdb8d48e89b31", + "waypointIndex": 11, + "longitude": 121.93548148861403, + "latitude": 30.89237131626793, + "altitude": -0.01, + "speed": 2, + "stayDuration": 0, + "headingAngle": 3, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点11", + "actions": null, + "remark": null + }, + { + "waypointId": "63ce643ec5c34d77b7609e46f0f6fd71", + "waypointIndex": 12, + "longitude": 121.93548516619276, + "latitude": 30.892531282684978, + "altitude": 0.01, + "speed": 2, + "stayDuration": 0, + "headingAngle": 1, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点12", + "actions": null, + "remark": null + }, + { + "waypointId": "4defc39a19b649909e4f0ce26445f2ff", + "waypointIndex": 13, + "longitude": 121.9354972473618, + "latitude": 30.89268805028157, + "altitude": -0.04, + "speed": 2, + "stayDuration": 0, + "headingAngle": 4, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点13", + "actions": null, + "remark": null + }, + { + "waypointId": "21a6090126274a9e9421d74250becfe6", + "waypointIndex": 14, + "longitude": 121.93549516441921, + "latitude": 30.892845036645927, + "altitude": -0.02, + "speed": 2, + "stayDuration": 0, + "headingAngle": 359, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点14", + "actions": null, + "remark": null + }, + { + "waypointId": "f327c0a95812476180767250de46748c", + "waypointIndex": 15, + "longitude": 121.93549438922788, + "latitude": 30.892988393509384, + "altitude": 0.04, + "speed": 2, + "stayDuration": 0, + "headingAngle": 360, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点15", + "actions": null, + "remark": null + }, + { + "waypointId": "07f290a3d44e45919389ae524677c1b5", + "waypointIndex": 16, + "longitude": 121.93553748217427, + "latitude": 30.89314989165774, + "altitude": 0.06, + "speed": 2, + "stayDuration": 0, + "headingAngle": 15, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点16", + "actions": null, + "remark": null + }, + { + "waypointId": "ef1f0a4973fe432aa8cd9066bfdd4316", + "waypointIndex": 17, + "longitude": 121.93559953246007, + "latitude": 30.893310258865725, + "altitude": 0.06, + "speed": 2, + "stayDuration": 0, + "headingAngle": 21, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点17", + "actions": null, + "remark": null + }, + { + "waypointId": "c3e651fbe829477096e54bd17be281ff", + "waypointIndex": 18, + "longitude": 121.93565224951432, + "latitude": 30.893520997292402, + "altitude": -0.01, + "speed": 2, + "stayDuration": 0, + "headingAngle": 14, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点18", + "actions": null, + "remark": null + }, + { + "waypointId": "163ccec434384ac8bdb115cf5550150a", + "waypointIndex": 19, + "longitude": 121.93559304007618, + "latitude": 30.893645941723907, + "altitude": 0.03, + "speed": 2, + "stayDuration": 0, + "headingAngle": 335, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点19", + "actions": null, + "remark": null + }, + { + "waypointId": "edf31d9816df4afbb7bb18cd8913556c", + "waypointIndex": 20, + "longitude": 121.93547984463055, + "latitude": 30.893745425029657, + "altitude": 0.01, + "speed": 2, + "stayDuration": 0, + "headingAngle": 311, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点20", + "actions": null, + "remark": null + }, + { + "waypointId": "11d5a4b1669b4da191ed0222868cec40", + "waypointIndex": 21, + "longitude": 121.93532940591656, + "latitude": 30.89376561346878, + "altitude": 0.07, + "speed": 2, + "stayDuration": 0, + "headingAngle": 278, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点21", + "actions": null, + "remark": null + }, + { + "waypointId": "eea9de82b474461a9f179f0318237993", + "waypointIndex": 22, + "longitude": 121.9352113679281, + "latitude": 30.893776277658056, + "altitude": -0.07, + "speed": 2, + "stayDuration": 0, + "headingAngle": 275, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点22", + "actions": null, + "remark": null + }, + { + "waypointId": "e940b4c11f354f5da9ec13d6528bcd5e", + "waypointIndex": 23, + "longitude": 121.93510901054175, + "latitude": 30.89378276162012, + "altitude": 0.01, + "speed": 2, + "stayDuration": 0, + "headingAngle": 274, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点23", + "actions": null, + "remark": null + }, + { + "waypointId": "46bee062d7db4a44a7711fb9a6178090", + "waypointIndex": 24, + "longitude": 121.93498594491533, + "latitude": 30.89378001240384, + "altitude": 0.03, + "speed": 2, + "stayDuration": 0, + "headingAngle": 269, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点24", + "actions": null, + "remark": null + }, + { + "waypointId": "a5c4249f7b35465b89c25c4b4837358b", + "waypointIndex": 25, + "longitude": 121.93489209066922, + "latitude": 30.893779304311394, + "altitude": -0.05, + "speed": 2, + "stayDuration": 0, + "headingAngle": 270, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点25", + "actions": null, + "remark": null + }, + { + "waypointId": "ad75664679374a638ba010a9ce81fa45", + "waypointIndex": 26, + "longitude": 121.93480007615194, + "latitude": 30.893767489414476, + "altitude": -0.06, + "speed": 2, + "stayDuration": 0, + "headingAngle": 263, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点26", + "actions": null, + "remark": null + }, + { + "waypointId": "188276cf3bc04106babcd24eb289887d", + "waypointIndex": 27, + "longitude": 121.93470987232504, + "latitude": 30.89374835801907, + "altitude": 0.07, + "speed": 2, + "stayDuration": 0, + "headingAngle": 258, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点27", + "actions": null, + "remark": null + }, + { + "waypointId": "541560856584414f8ac2961f265a107c", + "waypointIndex": 28, + "longitude": 121.93460461707542, + "latitude": 30.89374489319348, + "altitude": 0.01, + "speed": 2, + "stayDuration": 0, + "headingAngle": 268, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点28", + "actions": null, + "remark": null + }, + { + "waypointId": "b7bd1e678afb482ca17f1510c2efb39f", + "waypointIndex": 29, + "longitude": 121.93449084884726, + "latitude": 30.89374439697223, + "altitude": -0.05, + "speed": 2, + "stayDuration": 0, + "headingAngle": 270, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点29", + "actions": null, + "remark": null + }, + { + "waypointId": "a2059822ab7e4be692b8d8ed665df85a", + "waypointIndex": 30, + "longitude": 121.93434557030531, + "latitude": 30.893739381072535, + "altitude": 0.03, + "speed": 2, + "stayDuration": 0, + "headingAngle": 268, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点30", + "actions": null, + "remark": null + }, + { + "waypointId": "445f4f34332948e9adb28f75f80b28c0", + "waypointIndex": 31, + "longitude": 121.93423978373136, + "latitude": 30.893753609724925, + "altitude": 0.01, + "speed": 2, + "stayDuration": 0, + "headingAngle": 278, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点31", + "actions": null, + "remark": null + }, + { + "waypointId": "20c3242b8d9e47f89cd150da380731b2", + "waypointIndex": 32, + "longitude": 121.93410440533683, + "latitude": 30.893785434617637, + "altitude": -0.02, + "speed": 2, + "stayDuration": 0, + "headingAngle": 283, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点32", + "actions": null, + "remark": null + }, + { + "waypointId": "91d6e2176ee742f49d88d993ef1ba8d9", + "waypointIndex": 33, + "longitude": 121.9340248679004, + "latitude": 30.89388213835459, + "altitude": 0.03, + "speed": 2, + "stayDuration": 0, + "headingAngle": 321, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点33", + "actions": null, + "remark": null + }, + { + "waypointId": "14f00cf512224c61aab577e427ede6b8", + "waypointIndex": 34, + "longitude": 121.93403001624391, + "latitude": 30.89402031067838, + "altitude": -0.06, + "speed": 2, + "stayDuration": 0, + "headingAngle": 2, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点34", + "actions": null, + "remark": null + }, + { + "waypointId": "60230da03c1a42e69fac3aba539d345e", + "waypointIndex": 35, + "longitude": 121.93402444909374, + "latitude": 30.89413096294719, + "altitude": -0.05, + "speed": 2, + "stayDuration": 0, + "headingAngle": 357, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点35", + "actions": null, + "remark": null + }, + { + "waypointId": "99cce28907624b67930159da72cf1934", + "waypointIndex": 36, + "longitude": 121.93402261784053, + "latitude": 30.894312908495944, + "altitude": 0.02, + "speed": 2, + "stayDuration": 0, + "headingAngle": 359, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点36", + "actions": null, + "remark": null + }, + { + "waypointId": "559aa03b498c4d4ab6cf3199772d0ea4", + "waypointIndex": 37, + "longitude": 121.93402478702419, + "latitude": 30.894459221996772, + "altitude": -0.04, + "speed": 2, + "stayDuration": 0, + "headingAngle": 1, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点37", + "actions": null, + "remark": null + }, + { + "waypointId": "5344c90339954da28bf23ab0c7eb9201", + "waypointIndex": 38, + "longitude": 121.93376690250433, + "latitude": 30.89449680859644, + "altitude": -0.03, + "speed": 2, + "stayDuration": 0, + "headingAngle": 278, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点38", + "actions": null, + "remark": null + }, + { + "waypointId": "f68efd56064f411cb9695e0aa65d56a7", + "waypointIndex": 39, + "longitude": 121.93361669248003, + "latitude": 30.894502388130864, + "altitude": 0.09, + "speed": 2, + "stayDuration": 0, + "headingAngle": 272, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点39", + "actions": null, + "remark": null + }, + { + "waypointId": "1a28865b08754c15b06882fdd4a3e3fb", + "waypointIndex": 40, + "longitude": 121.93340628170232, + "latitude": 30.89449678551062, + "altitude": -0.03, + "speed": 2, + "stayDuration": 0, + "headingAngle": 268, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点40", + "actions": null, + "remark": null + }, + { + "waypointId": "c4eadf1bb8a744b593c3e6f89b5846ca", + "waypointIndex": 41, + "longitude": 121.93312119770555, + "latitude": 30.894492399593354, + "altitude": -0.02, + "speed": 2, + "stayDuration": 0, + "headingAngle": 269, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点41", + "actions": null, + "remark": null + }, + { + "waypointId": "0ffd6053b16949a892a79b1959a1053d", + "waypointIndex": 42, + "longitude": 121.93291600729209, + "latitude": 30.894487811217438, + "altitude": 0.1, + "speed": 2, + "stayDuration": 0, + "headingAngle": 269, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点42", + "actions": null, + "remark": null + }, + { + "waypointId": "1a36ce62c05a4e519f147ab290c4d6fa", + "waypointIndex": 43, + "longitude": 121.93270546912646, + "latitude": 30.8944963303201, + "altitude": 0.09, + "speed": 2, + "stayDuration": 0, + "headingAngle": 272, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点43", + "actions": null, + "remark": null + }, + { + "waypointId": "f8f5a8ed4e6841d8836b8fcefe157cb5", + "waypointIndex": 44, + "longitude": 121.93250790520669, + "latitude": 30.894495939598492, + "altitude": 0.04, + "speed": 2, + "stayDuration": 0, + "headingAngle": 270, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点44", + "actions": null, + "remark": null + }, + { + "waypointId": "33a68866025c46ae8976380674ae89f8", + "waypointIndex": 45, + "longitude": 121.93232562373203, + "latitude": 30.89449510142048, + "altitude": -0.05, + "speed": 2, + "stayDuration": 0, + "headingAngle": 270, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点45", + "actions": null, + "remark": null + }, + { + "waypointId": "28bfb988384a4294b51b3e8c9700e8e6", + "waypointIndex": 46, + "longitude": 121.93218577724376, + "latitude": 30.894461821360537, + "altitude": 0.07, + "speed": 2, + "stayDuration": 0, + "headingAngle": 257, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点46", + "actions": null, + "remark": null + }, + { + "waypointId": "aef63eb38a33491eb527c91d28587a1c", + "waypointIndex": 47, + "longitude": 121.93216876522885, + "latitude": 30.894405648806934, + "altitude": -0.05, + "speed": 2, + "stayDuration": 0, + "headingAngle": 197, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点47", + "actions": null, + "remark": null + }, + { + "waypointId": "09113d3eb42c488c9fd4082473add9da", + "waypointIndex": 48, + "longitude": 121.93216545235205, + "latitude": 30.894231045570407, + "altitude": 0.02, + "speed": 2, + "stayDuration": 0, + "headingAngle": 181, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点48", + "actions": null, + "remark": null + }, + { + "waypointId": "37710e28474e4dd69954e73994edf8a7", + "waypointIndex": 49, + "longitude": 121.93217544183047, + "latitude": 30.894095368522553, + "altitude": -0.03, + "speed": 2, + "stayDuration": 0, + "headingAngle": 176, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点49", + "actions": null, + "remark": null + }, + { + "waypointId": "8483ff877f30489e8527a72656ce17ac", + "waypointIndex": 50, + "longitude": 121.93215235163028, + "latitude": 30.8939343095108, + "altitude": 0.02, + "speed": 2, + "stayDuration": 0, + "headingAngle": 188, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点50", + "actions": null, + "remark": null + }, + { + "waypointId": "9cab3350ac7040e6be428abbeba099c9", + "waypointIndex": 51, + "longitude": 121.93209763478494, + "latitude": 30.89384355343672, + "altitude": 0.08, + "speed": 2, + "stayDuration": 0, + "headingAngle": 211, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点51", + "actions": null, + "remark": null + }, + { + "waypointId": "66815242ebf3417b9ea19f4b288cb3e9", + "waypointIndex": 52, + "longitude": 121.93202893929586, + "latitude": 30.893798966566195, + "altitude": 0.07, + "speed": 2, + "stayDuration": 0, + "headingAngle": 237, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点52", + "actions": null, + "remark": null + }, + { + "waypointId": "40e76d2b1a974836ac3ea36dae102464", + "waypointIndex": 53, + "longitude": 121.93186068310037, + "latitude": 30.89371854739938, + "altitude": 0.05, + "speed": 2, + "stayDuration": 0, + "headingAngle": 244, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点53", + "actions": null, + "remark": null + }, + { + "waypointId": "ad971284c13a460eb39841dfca7eaa39", + "waypointIndex": 54, + "longitude": 121.93174443347436, + "latitude": 30.893684169576197, + "altitude": -0.06, + "speed": 2, + "stayDuration": 0, + "headingAngle": 254, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点54", + "actions": null, + "remark": null + }, + { + "waypointId": "02a853f7e53a4ec9909df974d5a23368", + "waypointIndex": 55, + "longitude": 121.93151443781043, + "latitude": 30.89371751058461, + "altitude": 0.06, + "speed": 2, + "stayDuration": 0, + "headingAngle": 278, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点55", + "actions": null, + "remark": null + }, + { + "waypointId": "de42da94a76f4e34ab9ccc183fed9d32", + "waypointIndex": 56, + "longitude": 121.93121453898287, + "latitude": 30.893786479067202, + "altitude": 0.09, + "speed": 2, + "stayDuration": 0, + "headingAngle": 283, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点56", + "actions": null, + "remark": null + }, + { + "waypointId": "14e648dc95de4666915ad2256410986d", + "waypointIndex": 57, + "longitude": 121.93095705992852, + "latitude": 30.8938398414458, + "altitude": 0.05, + "speed": 2, + "stayDuration": 0, + "headingAngle": 282, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点57", + "actions": null, + "remark": null + }, + { + "waypointId": "974570963d4d443e90c7ff83a1eb0e76", + "waypointIndex": 58, + "longitude": 121.93077308131562, + "latitude": 30.89389375884373, + "altitude": -0.05, + "speed": 2, + "stayDuration": 0, + "headingAngle": 286, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点58", + "actions": null, + "remark": null + }, + { + "waypointId": "d22142cfc60e4615a12037431ca47738", + "waypointIndex": 59, + "longitude": 121.9305642893264, + "latitude": 30.893955372673062, + "altitude": -0.08, + "speed": 2, + "stayDuration": 0, + "headingAngle": 286, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点59", + "actions": null, + "remark": null + }, + { + "waypointId": "56c919ec1459459bbf341e60107415a9", + "waypointIndex": 60, + "longitude": 121.93033343724478, + "latitude": 30.89397116749783, + "altitude": 0.07, + "speed": 2, + "stayDuration": 0, + "headingAngle": 274, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点60", + "actions": null, + "remark": null + }, + { + "waypointId": "f9c1c53377ed40d5851ae063235e1090", + "waypointIndex": 61, + "longitude": 121.93016960815154, + "latitude": 30.89397493221634, + "altitude": 0.08, + "speed": 2, + "stayDuration": 0, + "headingAngle": 271, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点61", + "actions": null, + "remark": null + }, + { + "waypointId": "d2054d68d3264f42903909ef116845b1", + "waypointIndex": 62, + "longitude": 121.92993721377967, + "latitude": 30.893967453180295, + "altitude": 0.06, + "speed": 2, + "stayDuration": 0, + "headingAngle": 268, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点62", + "actions": null, + "remark": null + }, + { + "waypointId": "b4a22f7940e3449f8d510b0b8be206d3", + "waypointIndex": 63, + "longitude": 121.9297995520105, + "latitude": 30.89396705954325, + "altitude": 0.01, + "speed": 2, + "stayDuration": 0, + "headingAngle": 270, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点63", + "actions": null, + "remark": null + }, + { + "waypointId": "738f881820c94e78bb07fc4da9419abe", + "waypointIndex": 64, + "longitude": 121.92966092280739, + "latitude": 30.893989437848525, + "altitude": 0.08, + "speed": 2, + "stayDuration": 0, + "headingAngle": 279, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点64", + "actions": null, + "remark": null + }, + { + "waypointId": "029a01f077f741188f509a076031783b", + "waypointIndex": 65, + "longitude": 121.92949974782393, + "latitude": 30.89409441010552, + "altitude": -0.08, + "speed": 2, + "stayDuration": 0, + "headingAngle": 303, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点65", + "actions": null, + "remark": null + }, + { + "waypointId": "34165cb4b26d46ba8bf94abc50ca9813", + "waypointIndex": 66, + "longitude": 121.92934980341309, + "latitude": 30.894163875882608, + "altitude": -0.03, + "speed": 2, + "stayDuration": 0, + "headingAngle": 295, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点66", + "actions": null, + "remark": null + }, + { + "waypointId": "fb0ae38a66144267a346b94e5ab6ee26", + "waypointIndex": 67, + "longitude": 121.92917376953275, + "latitude": 30.89421933475959, + "altitude": 0.04, + "speed": 2, + "stayDuration": 0, + "headingAngle": 287, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点67", + "actions": null, + "remark": null + }, + { + "waypointId": "06c6fb5c45d242d0870794972450a459", + "waypointIndex": 68, + "longitude": 121.92897584217744, + "latitude": 30.894207488676457, + "altitude": 0.04, + "speed": 2, + "stayDuration": 0, + "headingAngle": 267, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点68", + "actions": null, + "remark": null + }, + { + "waypointId": "2e36fac8b63e4a0185d0c3933d95d43f", + "waypointIndex": 69, + "longitude": 121.92885123293783, + "latitude": 30.894128985735648, + "altitude": -0.05, + "speed": 2, + "stayDuration": 0, + "headingAngle": 238, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点69", + "actions": null, + "remark": null + }, + { + "waypointId": "ae77883629d9407e86cb2af915c18ba6", + "waypointIndex": 70, + "longitude": 121.92868422361651, + "latitude": 30.894028353953864, + "altitude": 0.06, + "speed": 2, + "stayDuration": 0, + "headingAngle": 239, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点70", + "actions": null, + "remark": null + }, + { + "waypointId": "f686cab245fe47a7be5d905a72b362b5", + "waypointIndex": 71, + "longitude": 121.9285127718929, + "latitude": 30.893953965292066, + "altitude": -0.09, + "speed": 2, + "stayDuration": 0, + "headingAngle": 247, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点71", + "actions": null, + "remark": null + }, + { + "waypointId": "6b296259d7824ef58daf4ae59f8bbcdc", + "waypointIndex": 72, + "longitude": 121.9283895281474, + "latitude": 30.893848951812718, + "altitude": 0.02, + "speed": 2, + "stayDuration": 0, + "headingAngle": 230, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点72", + "actions": null, + "remark": null + }, + { + "waypointId": "713968cefeee47f4aa38fd56d7097435", + "waypointIndex": 73, + "longitude": 121.92820880724548, + "latitude": 30.893714151361696, + "altitude": 0.08, + "speed": 2, + "stayDuration": 0, + "headingAngle": 233, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "航点73", + "actions": null, + "remark": null + }, + { + "waypointId": "a78793a29e9d4735ab68b9aca77f8acb", + "waypointIndex": 74, + "longitude": 121.9281979067755, + "latitude": 30.893500907105462, + "altitude": -0.02, + "speed": 2, + "stayDuration": 0, + "headingAngle": 183, + "turnMode": "smooth", + "isKeyPoint": false, + "pointName": "终点", + "actions": null, + "remark": null + } + ], + "createTime": "2026-04-12 01:01:58", + "updateTime": "2026-04-12 01:01:58" +} \ No newline at end of file diff --git a/zlt-web/yingyan/src/pages/client/components/CenterView/index.less b/zlt-web/yingyan/src/pages/client/components/CenterView/index.less index a565434a..d848bc07 100644 --- a/zlt-web/yingyan/src/pages/client/components/CenterView/index.less +++ b/zlt-web/yingyan/src/pages/client/components/CenterView/index.less @@ -36,6 +36,36 @@ border: 1px solid rgba(34, 211, 238, 0.3); } +.viewSwitchBar { + position: absolute; + top: 18px; + right: 18px; + display: flex; + align-items: center; + gap: 10px; + z-index: 30; +} + +.viewSwitchBtn { + height: 34px; + padding: 0 14px; + border: 1px solid rgba(34, 211, 238, 0.35); + border-radius: 999px; + background: rgba(8, 15, 28, 0.82); + color: #d8f6ff; + font-size: 12px; + font-weight: 600; + cursor: pointer; + backdrop-filter: blur(8px); + transition: all 0.2s ease; + + &:hover { + border-color: rgba(34, 211, 238, 0.7); + color: #fff; + box-shadow: 0 0 0 1px rgba(34, 211, 238, 0.18), 0 8px 22px rgba(0, 0, 0, 0.22); + } +} + .loadingSpinner { width: 16px; height: 16px; diff --git a/zlt-web/yingyan/src/pages/client/components/CenterView/index.tsx b/zlt-web/yingyan/src/pages/client/components/CenterView/index.tsx index 4366e19c..86247115 100644 --- a/zlt-web/yingyan/src/pages/client/components/CenterView/index.tsx +++ b/zlt-web/yingyan/src/pages/client/components/CenterView/index.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useRef, useState, useCallback } from 'react'; +import React, { useCallback, useEffect, useRef, useState } from 'react'; import { App } from 'antd'; import { useTilesetLoader } from '@/pages/map3d/components/MapContainer/3d/hooks/useTilesetLoader'; import { useCesiumRouteLibraryRenderer } from '@/pages/map3d/components/RouteEditor/hooks/useCesiumRouteLibraryRenderer'; @@ -25,30 +25,56 @@ interface CenterViewProps { onPreviewChange?: (previewing: boolean) => void; } -const CenterView: React.FC = ({ deviceSn, routes, selectedRouteId, boatData, onModelCenter, isSailing, sailingLoading, previewStartSignal, previewStopSignal, onStartSailing, onPreviewChange }) => { +const ACTUAL_TRACK_ID = 'client-actual-track'; + +const CenterView: React.FC = ({ + deviceSn, + routes, + selectedRouteId, + boatData, + onModelCenter, + isSailing, + previewStartSignal, + previewStopSignal, + onPreviewChange, +}) => { const containerRef = useRef(null); const viewerRef = useRef(null); - const [viewerReady, setViewerReady] = useState(false); - const [modelLoading, setModelLoading] = useState(false); const boatEntityRef = useRef(null); + const firstTilesetRef = useRef(null); + const loadedModelDeviceRef = useRef(null); const trackPositionsRef = useRef([]); const terrainLoadedRef = useRef(false); - const sailingCameraStateRef = useRef(null); - const sailingInitialViewRouteRef = useRef(null); const initRetryCountRef = useRef(0); + const hasFlownToBoatRef = useRef(false); + const activeTrackRouteRef = useRef(null); + const previousSelectedRouteRef = useRef(selectedRouteId); + const routeDetailCacheRef = useRef>(new Map()); + const [viewerReady, setViewerReady] = useState(false); + const [modelLoading, setModelLoading] = useState(false); + const [hasLoadedModel, setHasLoadedModel] = useState(false); + const [modelLoadEnabled, setModelLoadEnabled] = useState(false); + const [routeRenderItems, setRouteRenderItems] = useState([]); const { message: messageApi } = App.useApp(); const { loadTileset, unloadAllTilesets } = useTilesetLoader(); - const { isPreviewing, startPreview, stopPreview } = useRoutePreview({ viewerRef, messageApi }); + const { flyToRoute: flyToRouteLibrary, getRouteSurfaceGeometry } = useCesiumRouteLibraryRenderer({ + viewerRef, + routes: routeRenderItems, + }); + const { isPreviewing, startPreview, stopPreview } = useRoutePreview({ + viewerRef, + messageApi, + getRouteSurfaceGeometry, + }); + + const hasBoatPosition = Number.isFinite(boatData?.longitude) && Number.isFinite(boatData?.latitude); - // 预览状态变化时通知父组件 useEffect(() => { onPreviewChange?.(isPreviewing); }, [isPreviewing, onPreviewChange]); const lastPreviewStopSignalRef = useRef(previewStopSignal); - - // 外部停止通道:例如 HUD 点击"结束预览"时由父组件递增信号 useEffect(() => { if (previewStopSignal == null) return; if (lastPreviewStopSignalRef.current === previewStopSignal) return; @@ -59,64 +85,123 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute } }, [previewStopSignal, isPreviewing, stopPreview]); - // 外部启动预览通道:LeftPanel 点击"预览航线"时由父组件递增信号 const lastPreviewStartSignalRef = useRef(previewStartSignal); useEffect(() => { if (previewStartSignal == null) return; if (lastPreviewStartSignalRef.current === previewStartSignal) return; lastPreviewStartSignalRef.current = previewStartSignal; - // 延迟执行,等航线航点数据加载完成 const timer = setTimeout(() => { const waypoints = routeDetailCacheRef.current.get(selectedRouteId || ''); if (waypoints && waypoints.length >= 2) { - startPreview(waypoints, 2); + startPreview(waypoints, 2, selectedRouteId || undefined); } else { - messageApi.warning('航点数据不足或未加载,无法预览'); + messageApi.warning('航点数据不足或尚未加载,无法预览航线'); } }, 300); + return () => clearTimeout(timer); }, [previewStartSignal, selectedRouteId, startPreview, messageApi]); - // 航线渲染数据(含航点) - const [routeRenderItems, setRouteRenderItems] = useState([]); - // 缓存已加载的航线详情 - const routeDetailCacheRef = useRef>(new Map()); - - const { flyToRoute: flyToRouteLibrary } = useCesiumRouteLibraryRenderer({ - viewerRef, - routes: routeRenderItems, - }); - - // 检查容器尺寸是否有效 const isContainerValid = useCallback(() => { if (!containerRef.current) return false; const rect = containerRef.current.getBoundingClientRect(); return rect.width > 0 && rect.height > 0; }, []); - // 初始化 Cesium(参考鹰眼 CesiumContainer 初始化模式) + const offsetPositionUp = useCallback((origin: any, upMeters: number) => { + if (!origin || !Cesium || !Cesium.Transforms?.eastNorthUpToFixedFrame || !Cesium.Matrix4?.multiplyByPoint) { + return origin; + } + + try { + const enu = Cesium.Transforms.eastNorthUpToFixedFrame(origin); + return Cesium.Matrix4.multiplyByPoint(enu, new Cesium.Cartesian3(0, 0, upMeters), new Cesium.Cartesian3()); + } catch { + return origin; + } + }, []); + + const resolveBoatWorldPosition = useCallback((longitude: number, latitude: number) => { + if (!Cesium) return null; + + const basePosition = Cesium.Cartesian3.fromDegrees(longitude, latitude, 0); + const viewer = viewerRef.current; + if (!viewer || viewer.isDestroyed?.() || !viewer.scene?.clampToHeight) { + return offsetPositionUp(basePosition, 1.2); + } + + try { + const excluded = boatEntityRef.current ? [boatEntityRef.current] : []; + const clamped = viewer.scene.clampToHeight(basePosition, excluded); + if (clamped) { + return offsetPositionUp(clamped, 1.2); + } + } catch { + // 忽略贴地失败,回退到基础坐标 + } + + return offsetPositionUp(basePosition, 1.2); + }, [offsetPositionUp]); + + const flyToBoatOverview = useCallback((duration = 1.2) => { + if (!Cesium || !viewerRef.current || viewerRef.current.isDestroyed?.()) return; + if (!hasBoatPosition || isPreviewing || isSailing) return; + + const position = resolveBoatWorldPosition(boatData!.longitude, boatData!.latitude); + if (!position) return; + + try { + viewerRef.current.camera.cancelFlight?.(); + viewerRef.current.camera.flyToBoundingSphere(new Cesium.BoundingSphere(position, 18), { + offset: new Cesium.HeadingPitchRange( + Cesium.Math.toRadians(0), + Cesium.Math.toRadians(-54), + 360, + ), + duration, + }); + hasFlownToBoatRef.current = true; + viewerRef.current.scene?.requestRender?.(); + } catch { + // 忽略相机异常 + } + }, [boatData, hasBoatPosition, isPreviewing, isSailing, resolveBoatWorldPosition]); + + const flyToModelOverview = useCallback((duration = 1.2) => { + if (!Cesium || !viewerRef.current || viewerRef.current.isDestroyed?.()) return; + const tileset = firstTilesetRef.current; + if (!tileset?.boundingSphere) return; + + try { + viewerRef.current.camera.cancelFlight?.(); + viewerRef.current.camera.flyToBoundingSphere(tileset.boundingSphere, { + offset: new Cesium.HeadingPitchRange( + Cesium.Math.toRadians(0), + Cesium.Math.toRadians(-42), + Math.max(tileset.boundingSphere.radius * 2.4, 280), + ), + duration, + }); + viewerRef.current.scene?.requestRender?.(); + } catch { + // 忽略相机异常 + } + }, []); + useEffect(() => { let destroyed = false; let retryTimer: ReturnType | null = null; const initCesium = async () => { - // 检查容器是否有效 - if (!containerRef.current) { - console.warn('[CenterView] 容器未就绪'); - return; - } + if (!containerRef.current) return; - // 关键修复:检查容器尺寸 if (!isContainerValid()) { - console.warn('[CenterView] 容器尺寸无效,延迟初始化'); if (initRetryCountRef.current < 10) { - initRetryCountRef.current++; + initRetryCountRef.current += 1; retryTimer = setTimeout(() => { if (!destroyed) initCesium(); }, 100); - } else { - console.error('[CenterView] 容器尺寸始终无效,初始化失败'); } return; } @@ -126,17 +211,14 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute Cesium = cesiumModule; (window as any).Cesium = cesiumModule; - // 设置 Worker 基础路径,避免从 file:/// 加载 const cesiumBaseUrl = process.env.CESIUM_BASE_URL || '/'; Cesium.buildModuleUrl.setBaseUrl(`${cesiumBaseUrl}cesium/`); - // 设置 Cesium Ion Token const cesiumToken = process.env.REACT_APP_CESIUM_TOKEN; if (cesiumToken) { Cesium.Ion.defaultAccessToken = cesiumToken; } - // 加载 Cesium CSS if (!document.querySelector('link[href*="cesium"]')) { const link = document.createElement('link'); link.rel = 'stylesheet'; @@ -145,19 +227,7 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute } } - if (destroyed) return; - - // 再次检查容器尺寸(双重保险) - if (!isContainerValid()) { - console.warn('[CenterView] 初始化前容器尺寸再次检查失败'); - if (initRetryCountRef.current < 10) { - initRetryCountRef.current++; - retryTimer = setTimeout(() => { - if (!destroyed) initCesium(); - }, 100); - } - return; - } + if (destroyed || !isContainerValid()) return; try { const viewer = new Cesium.Viewer(containerRef.current, { @@ -178,7 +248,6 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute maximumRenderTimeChange: Infinity, }); - // 移除默认图层,添加 ArcGIS 影像 viewer.imageryLayers.remove(viewer.imageryLayers.get(0)); viewer.scene.globe.baseColor = Cesium.Color.fromCssColorString('#1e4d7b'); viewer.imageryLayers.addImageryProvider( @@ -186,27 +255,24 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', minimumLevel: 0, maximumLevel: 18, - }) + }), ); viewer.scene.globe.enableLighting = false; viewer.scene.skyAtmosphere.show = true; - viewerRef.current = viewer; - setViewerReady(true); - initRetryCountRef.current = 0; // 重置重试计数 - - // 隐藏 Cesium 水印 const creditContainer = viewer.cesiumWidget?.creditContainer; if (creditContainer) { creditContainer.style.display = 'none'; } - console.log('[CenterView] Cesium 初始化成功'); + viewerRef.current = viewer; + setViewerReady(true); + initRetryCountRef.current = 0; } catch (error) { - console.error('[CenterView] Cesium 初始化失败:', error); + console.error('[CenterView] Cesium 初始化失败', error); if (initRetryCountRef.current < 3) { - initRetryCountRef.current++; + initRetryCountRef.current += 1; retryTimer = setTimeout(() => { if (!destroyed) initCesium(); }, 500); @@ -223,19 +289,55 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute try { unloadAllTilesets(viewerRef.current); viewerRef.current.destroy(); - } catch (e) { - console.warn('[CenterView] Viewer 销毁时出错:', e); + } catch (error) { + console.warn('[CenterView] Viewer 销毁失败', error); } viewerRef.current = null; } + firstTilesetRef.current = null; + loadedModelDeviceRef.current = null; + setHasLoadedModel(false); setViewerReady(false); }; }, [isContainerValid, unloadAllTilesets]); - /** - * 动态切换高程地形(参考鹰眼 switchToElevationTerrain) - * 根据模型配置的地形类型,优先尝试对应地形,失败后降级 - */ + useEffect(() => { + if (!viewerReady) return; + const viewer = viewerRef.current; + const container = containerRef.current; + if (!viewer || viewer.isDestroyed?.() || !container) return; + + let resizeTimer: ReturnType | null = null; + + const handleResize = () => { + if (resizeTimer) clearTimeout(resizeTimer); + resizeTimer = setTimeout(() => { + const currentViewer = viewerRef.current; + if (!currentViewer || currentViewer.isDestroyed?.()) return; + try { + currentViewer.resize?.(); + currentViewer.scene?.requestRender?.(); + } catch { + // 忽略 resize 异常 + } + }, 60); + }; + + const observer = typeof ResizeObserver !== 'undefined' + ? new ResizeObserver(() => handleResize()) + : null; + + observer?.observe(container); + window.addEventListener('resize', handleResize); + handleResize(); + + return () => { + if (resizeTimer) clearTimeout(resizeTimer); + observer?.disconnect(); + window.removeEventListener('resize', handleResize); + }; + }, [viewerReady]); + const switchToElevationTerrain = useCallback(async (preferredTerrainType?: string): Promise => { if (!viewerRef.current || !Cesium) return 'ellipsoid'; if (terrainLoadedRef.current && !preferredTerrainType) return 'loaded'; @@ -245,7 +347,7 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute if (preferredTerrainType === 'arcgis') { try { const terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl( - 'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer' + 'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer', ); viewerRef.current.terrainProvider = terrainProvider; viewerRef.current.scene.globe.depthTestAgainstTerrain = true; @@ -278,7 +380,7 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute } catch { try { const terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl( - 'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer' + 'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer', ); viewerRef.current.terrainProvider = terrainProvider; viewerRef.current.scene.globe.depthTestAgainstTerrain = true; @@ -293,13 +395,16 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute return loadedTerrainType; }, []); - // 加载3D模型(参考鹰眼 loadDeviceModels) useEffect(() => { - if (!viewerReady || !deviceSn) return; + if (!viewerReady || !deviceSn || !modelLoadEnabled) return; + if (loadedModelDeviceRef.current === deviceSn && firstTilesetRef.current) return; let cancelled = false; const loadModels = async () => { setModelLoading(true); + setHasLoadedModel(false); + firstTilesetRef.current = null; + loadedModelDeviceRef.current = null; unloadAllTilesets(viewerRef.current); try { @@ -311,20 +416,17 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute } const configs = modelList.map((model: any) => convertToTilesetConfig(model)); - - // 并行:高程地形加载 + 模型准备 const firstTerrainType = configs[0]?.position?.terrainType; const terrainPromise = switchToElevationTerrain(firstTerrainType); - const autoLoadCount = configs.length <= 2 ? configs.length : 1; const configsToLoad = configs.slice(0, autoLoadCount); - - // 等待高程加载完成 const loadedTerrainType = await terrainPromise; - if (cancelled) { setModelLoading(false); return; } + if (cancelled) { + setModelLoading(false); + return; + } let firstTileset: any = null; - for (const config of configsToLoad) { if (!config.url) continue; const tileset = await loadTileset(config, viewerRef.current, Cesium, loadedTerrainType); @@ -333,42 +435,53 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute } } - // 模型加载完成后飞到模型位置 - if (firstTileset && viewerRef.current && !viewerRef.current.isDestroyed?.()) { - try { - const radius = Number(firstTileset?.boundingSphere?.radius); - const range = Number.isFinite(radius) && radius > 0 ? Math.max(50, radius * 0.8) : 100; - viewerRef.current.flyTo(firstTileset, { - duration: 1.5, - offset: new Cesium.HeadingPitchRange( - Cesium.Math.toRadians(0), - Cesium.Math.toRadians(-50), - range - ), - }); - // 通知父组件模型中心位置(用于模拟数据定位) - if (onModelCenter && firstTileset.boundingSphere?.center) { - const cartographic = Cesium.Cartographic.fromCartesian(firstTileset.boundingSphere.center); - onModelCenter( - Cesium.Math.toDegrees(cartographic.longitude), - Cesium.Math.toDegrees(cartographic.latitude), - ); + firstTilesetRef.current = firstTileset; + loadedModelDeviceRef.current = firstTileset ? deviceSn : null; + setHasLoadedModel(!!firstTileset); + + if (onModelCenter && firstTileset?.boundingSphere?.center) { + const cartographic = Cesium.Cartographic.fromCartesian(firstTileset.boundingSphere.center); + onModelCenter( + Cesium.Math.toDegrees(cartographic.longitude), + Cesium.Math.toDegrees(cartographic.latitude), + ); + } + + if ( + firstTileset + && !hasBoatPosition + && !selectedRouteId + && !isPreviewing + && !isSailing + ) { + setTimeout(() => { + if (!cancelled) { + flyToModelOverview(1.25); } - } catch (e) { - console.warn('飞到模型位置失败:', e); - } + }, 120); } } catch (error) { - console.error('加载设备模型失败:', error); + console.error('加载设备模型失败', error); } + setModelLoading(false); }; loadModels(); - return () => { cancelled = true; }; - }, [viewerReady, deviceSn, switchToElevationTerrain, loadTileset, unloadAllTilesets, onModelCenter]); + return () => { + cancelled = true; + }; + }, [ + viewerReady, + deviceSn, + modelLoadEnabled, + switchToElevationTerrain, + loadTileset, + unloadAllTilesets, + onModelCenter, + flyToModelOverview, + ]); - // 选中航线时加载航点详情并渲染 useEffect(() => { if (!viewerReady || !selectedRouteId) { setRouteRenderItems([]); @@ -382,302 +495,301 @@ const CenterView: React.FC = ({ deviceSn, routes, selectedRoute try { const res = await getBoatRouteDetail(selectedRouteId); if (res.resp_code === 0 && res.data?.waypoints) { - waypoints = res.data.waypoints.map((wp) => ({ - longitude: wp.longitude, - latitude: wp.latitude, - speed: wp.speed, - stayDuration: wp.stayDuration, - pointName: wp.pointName, + waypoints = res.data.waypoints.map((waypoint) => ({ + longitude: waypoint.longitude, + latitude: waypoint.latitude, + speed: waypoint.speed, + stayDuration: waypoint.stayDuration, + pointName: waypoint.pointName, })); routeDetailCacheRef.current.set(selectedRouteId, waypoints); } } catch { - messageApi.error('线路详情加载失败'); + messageApi.error('航线详情加载失败'); return; } } if (waypoints && waypoints.length > 0) { - setRouteRenderItems([{ - routeId: selectedRouteId, - routeName: routes.find((r) => r.routeId === selectedRouteId)?.routeName || '', - waypoints, - visible: true, - highlighted: true, - }]); - // 普通浏览模式下飞到航线总览;执行/预览模式由专用相机逻辑接管 - if (!isSailing && !isPreviewing) { - setTimeout(() => flyToRouteLibrary(selectedRouteId), 100); - } + setRouteRenderItems([ + { + routeId: selectedRouteId, + routeName: routes.find((route) => route.routeId === selectedRouteId)?.routeName || '', + waypoints, + visible: true, + highlighted: true, + }, + ]); } }; loadAndRender(); - }, [viewerReady, selectedRouteId, routes, flyToRouteLibrary, isSailing, isPreviewing]); + }, [viewerReady, selectedRouteId, routes, messageApi]); + + useEffect(() => { + if (!viewerReady || !selectedRouteId || isPreviewing) return; + + const timer = setTimeout(() => { + flyToRouteLibrary(selectedRouteId); + }, isSailing ? 140 : 100); + + return () => clearTimeout(timer); + }, [viewerReady, selectedRouteId, isPreviewing, isSailing, flyToRouteLibrary]); + + useEffect(() => { + setModelLoadEnabled(false); + hasFlownToBoatRef.current = false; + firstTilesetRef.current = null; + loadedModelDeviceRef.current = null; + setHasLoadedModel(false); + }, [deviceSn]); + + useEffect(() => { + if (!viewerReady || !deviceSn) return; + + if (selectedRouteId || isPreviewing || isSailing) { + setModelLoadEnabled(true); + return; + } + + if (hasBoatPosition) { + setModelLoadEnabled(true); + return; + } + + if (!hasBoatPosition) { + const timer = setTimeout(() => { + setModelLoadEnabled(true); + }, 1500); + return () => clearTimeout(timer); + } + + return undefined; + }, [viewerReady, deviceSn, selectedRouteId, isPreviewing, isSailing, hasBoatPosition]); + + useEffect(() => { + if (!viewerReady || !hasBoatPosition || selectedRouteId || isPreviewing || isSailing || hasFlownToBoatRef.current) { + return; + } + + const timer = setTimeout(() => { + flyToBoatOverview(1.1); + }, 120); + + return () => clearTimeout(timer); + }, [viewerReady, hasBoatPosition, selectedRouteId, isPreviewing, isSailing, flyToBoatOverview]); + + useEffect(() => { + const previousSelectedRoute = previousSelectedRouteRef.current; + const canceledRouteSelection = !!previousSelectedRoute && !selectedRouteId; + + if (viewerReady && canceledRouteSelection && hasBoatPosition && !isPreviewing && !isSailing) { + const timer = setTimeout(() => { + flyToBoatOverview(0.95); + }, 80); + previousSelectedRouteRef.current = selectedRouteId; + return () => clearTimeout(timer); + } + + previousSelectedRouteRef.current = selectedRouteId; + return undefined; + }, [viewerReady, selectedRouteId, hasBoatPosition, isPreviewing, isSailing, flyToBoatOverview]); - // 实时船位渲染 useEffect(() => { if (!viewerReady || !Cesium) return; const viewer = viewerRef.current; - if (!viewer || viewer.isDestroyed()) return; + if (!viewer || viewer.isDestroyed?.()) return; - let position: any = null; - let headingRad = 0; - let shouldTrack = false; - - if (boatData?.longitude && boatData?.latitude) { - position = Cesium.Cartesian3.fromDegrees(boatData.longitude, boatData.latitude, 2); - headingRad = Cesium.Math.toRadians(boatData.heading || 0); - shouldTrack = true; - } else if (isSailing && selectedRouteId) { - const waypoints = routeDetailCacheRef.current.get(selectedRouteId) || []; - if (waypoints.length >= 1) { - const wp0 = waypoints[0]; - const wp1 = waypoints[1] || wp0; - const dLon = (wp1.longitude - wp0.longitude) * Math.PI / 180; - const lat1 = wp0.latitude * Math.PI / 180; - const lat2 = wp1.latitude * Math.PI / 180; - const y = Math.sin(dLon) * Math.cos(lat2); - const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon); - headingRad = Math.atan2(y, x); - position = Cesium.Cartesian3.fromDegrees(wp0.longitude, wp0.latitude, 2); - } - } - - if (!position) { - if (boatEntityRef.current && !isSailing) { + if (isPreviewing) { + if (boatEntityRef.current) { try { viewer.entities.remove(boatEntityRef.current); - } catch { /* ignore */ } + } catch { + // 忽略清理异常 + } boatEntityRef.current = null; } return; } - const MODEL_HEADING_OFFSET = -Math.PI / 2; + if (!hasBoatPosition) { + if (boatEntityRef.current) { + try { + viewer.entities.remove(boatEntityRef.current); + } catch { + // 忽略清理异常 + } + boatEntityRef.current = null; + } + return; + } + + const liftedPosition = resolveBoatWorldPosition(boatData!.longitude, boatData!.latitude); + if (!liftedPosition) return; + + const headingRad = Cesium.Math.toRadians(boatData?.heading || 0); const orientation = Cesium.Transforms?.headingPitchRollQuaternion ? Cesium.Transforms.headingPitchRollQuaternion( - position, - new Cesium.HeadingPitchRoll(headingRad + MODEL_HEADING_OFFSET, 0, 0), + liftedPosition, + new Cesium.HeadingPitchRoll(headingRad - Math.PI / 2, 0, 0), ) : undefined; - if (shouldTrack) { - trackPositionsRef.current.push(position); - // 限制轨迹点数 - if (trackPositionsRef.current.length > 500) { - trackPositionsRef.current = trackPositionsRef.current.slice(-400); - } - } - - // 更新/创建船位 Entity if (!boatEntityRef.current) { boatEntityRef.current = viewer.entities.add({ - position, + position: liftedPosition, orientation, + point: { + pixelSize: 20, + color: Cesium.Color.fromCssColorString('#22d3ee'), + outlineColor: Cesium.Color.WHITE, + outlineWidth: 3, + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, model: { uri: `${process.env.CESIUM_BASE_URL || '/'}chuan-model.glb`, - scale: 0.001, - minimumPixelSize: 64, - maximumScale: 200, + scale: 0.0015, + minimumPixelSize: 96, + maximumScale: 220, runAnimations: true, colorBlendMode: Cesium.ColorBlendMode.HIGHLIGHT, color: Cesium.Color.WHITE, - silhouetteSize: 0, - heightReference: Cesium.HeightReference?.CLAMP_TO_3D_TILE || Cesium.HeightReference?.RELATIVE_TO_GROUND || undefined, + silhouetteColor: Cesium.Color.fromCssColorString('#22d3ee').withAlpha(0.95), + silhouetteSize: 1.5, }, label: { - text: '当前位置', - font: '12px sans-serif', + text: '无人船', + font: '600 14px sans-serif', fillColor: Cesium.Color.WHITE, style: Cesium.LabelStyle.FILL_AND_OUTLINE, outlineWidth: 2, outlineColor: Cesium.Color.BLACK, + showBackground: true, + backgroundColor: Cesium.Color.fromCssColorString('#082f49').withAlpha(0.88), verticalOrigin: Cesium.VerticalOrigin.BOTTOM, - pixelOffset: new Cesium.Cartesian2(0, -16), - }, }); + pixelOffset: new Cesium.Cartesian2(0, -34), + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, + }); } else { - boatEntityRef.current.position = position; + boatEntityRef.current.position = liftedPosition; if (orientation) { boatEntityRef.current.orientation = orientation; } } - // 轨迹线 - if (shouldTrack && trackPositionsRef.current.length >= 2) { - const trackId = 'client-boat-track'; - let trackEntity = viewer.entities.getById(trackId); - if (!trackEntity) { - viewer.entities.add({ - id: trackId, - polyline: { - positions: new Cesium.CallbackProperty(() => trackPositionsRef.current, false), - width: 3, - material: new Cesium.PolylineGlowMaterialProperty({ - glowPower: 0.3, - color: Cesium.Color.LIME, - }), - clampToGround: true, - }, - }); - } - } + viewer.scene.requestRender?.(); + }, [viewerReady, boatData, hasBoatPosition, isPreviewing, resolveBoatWorldPosition]); - viewer.scene.requestRender(); - }, [viewerReady, boatData, isSailing, selectedRouteId, routeRenderItems]); - - // 执行航线时第一视角跟踪(与预览模式相同的追踪相机) useEffect(() => { if (!viewerReady || !Cesium) return; const viewer = viewerRef.current; - if (!viewer || viewer.isDestroyed()) return; + if (!viewer || viewer.isDestroyed?.()) return; - const setInitialSailingView = (waypoints: BoatWaypointDTO[]) => { - if (!selectedRouteId || !waypoints || waypoints.length < 2) return false; + const clearTrack = () => { + trackPositionsRef.current = []; try { - const wp0 = waypoints[0]; - const wp1 = waypoints[1]; - - // 计算从点0到点1的航向角 - const dLon = (wp1.longitude - wp0.longitude) * Math.PI / 180; - const lat1 = wp0.latitude * Math.PI / 180; - const lat2 = wp1.latitude * Math.PI / 180; - const y = Math.sin(dLon) * Math.cos(lat2); - const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon); - const headingRad = Math.atan2(y, x); - - // 为了让第一个航点在视野中可见,我们需要将相机放置在第一个航点“后方”一段距离,并抬高一定高度 - // 根据 headingRad 将相机向反方向平移 - const offsetDistance = 60; // 距离航点 60 米远 - const height = 40; // 相机高度 40 米 - - // 使用简单的经纬度偏移近似(适用于小范围),也可以用球体推算 - // 1纬度大约111公里,1经度随纬度变化。使用简单的三角函数反推相机位置 - const R = 6378137; // 地球半径 - const camDLat = -offsetDistance * Math.cos(headingRad) / R; - const camDLon = -offsetDistance * Math.sin(headingRad) / (R * Math.cos(Math.PI * wp0.latitude / 180)); - - const camLat = wp0.latitude + camDLat * 180 / Math.PI; - const camLon = wp0.longitude + camDLon * 180 / Math.PI; - viewer.camera.setView({ - destination: Cesium.Cartesian3.fromDegrees(camLon, camLat, height), - orientation: { - heading: headingRad, - pitch: Cesium.Math.toRadians(-25), // 稍微向下俯视 - roll: 0 - } - }); viewer.scene.requestRender(); - return true; + viewer.entities.removeById(ACTUAL_TRACK_ID); } catch { - return false; + // 忽略清理异常 } }; - if (isSailing) { - // 首次进入执行模式:保存相机,飞到第一个航点上方 - if (!sailingCameraStateRef.current) { - sailingCameraStateRef.current = { - position: viewer.camera.position.clone(), - heading: viewer.camera.heading, - pitch: viewer.camera.pitch, - roll: viewer.camera.roll, - }; - sailingInitialViewRouteRef.current = null; - } - - const waypoints = routeDetailCacheRef.current.get(selectedRouteId || ''); - if ((!boatData?.longitude || !boatData?.latitude) && waypoints && waypoints.length >= 2) { - if (sailingInitialViewRouteRef.current !== selectedRouteId) { - const ok = setInitialSailingView(waypoints); - if (ok) { - sailingInitialViewRouteRef.current = selectedRouteId || null; - } - } - return; - } - - // 有实际船位数据时:跟随船位 - if (boatData?.longitude && boatData?.latitude) { - try { - const headingRad = Cesium.Math.toRadians(boatData.heading || 0); - const position = Cesium.Cartesian3.fromDegrees(boatData.longitude, boatData.latitude, 2); - const enu = Cesium.Transforms.eastNorthUpToFixedFrame(position); - const localUp = new Cesium.Cartesian3(0, 0, 0.8); - const target = Cesium.Matrix4.multiplyByPoint(enu, localUp, new Cesium.Cartesian3()); - viewer.camera.lookAt( - target, - new Cesium.HeadingPitchRange(headingRad, Cesium.Math.toRadians(-20), 22), - ); - viewer.scene.requestRender(); - } catch { - try { - viewer.camera.setView({ - destination: Cesium.Cartesian3.fromDegrees(boatData.longitude, boatData.latitude, 25), - orientation: { - heading: Cesium.Math.toRadians(boatData.heading || 0), - pitch: Cesium.Math.toRadians(-20), - roll: 0, - }, - }); - } catch { /* ignore */ } - } - } - } - - // 退出执行模式:恢复相机 - if (!isSailing && sailingCameraStateRef.current) { - try { - if (Cesium?.Matrix4) { - viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY); - } - } catch { /* ignore */ } - try { - viewer.camera.setView({ - destination: sailingCameraStateRef.current.position, - orientation: { - heading: sailingCameraStateRef.current.heading, - pitch: sailingCameraStateRef.current.pitch, - roll: sailingCameraStateRef.current.roll, - }, - }); - } catch { /* ignore */ } - sailingCameraStateRef.current = null; - sailingInitialViewRouteRef.current = null; - } - }, [viewerReady, isSailing, boatData, selectedRouteId, routeRenderItems, flyToRouteLibrary]); - - // 预览选中航线(供外部调用,通过 ref 或直接调用) - const handlePreviewRoute = useCallback(async () => { - if (!selectedRouteId) return; - const waypoints = routeDetailCacheRef.current.get(selectedRouteId); - if (!waypoints || waypoints.length < 2) { - messageApi.warning('航点数据不足,无法预览'); + if (!isSailing || !selectedRouteId) { + activeTrackRouteRef.current = null; + clearTrack(); return; } - await startPreview(waypoints, 2); - }, [selectedRouteId, startPreview, messageApi]); + + if (activeTrackRouteRef.current !== selectedRouteId) { + activeTrackRouteRef.current = selectedRouteId; + clearTrack(); + } + }, [viewerReady, isSailing, selectedRouteId]); + + useEffect(() => { + if (!viewerReady || !Cesium || !isSailing || isPreviewing || !hasBoatPosition) return; + const viewer = viewerRef.current; + if (!viewer || viewer.isDestroyed?.()) return; + + const position = Cesium.Cartesian3.fromDegrees(boatData!.longitude, boatData!.latitude, 0); + const lastPosition = trackPositionsRef.current[trackPositionsRef.current.length - 1]; + if (!lastPosition || Cesium.Cartesian3.distance(lastPosition, position) > 0.3) { + trackPositionsRef.current.push(position); + } + + if (trackPositionsRef.current.length > 600) { + trackPositionsRef.current = trackPositionsRef.current.slice(-500); + } + + let trackEntity = viewer.entities.getById(ACTUAL_TRACK_ID); + if (!trackEntity) { + trackEntity = viewer.entities.add({ + id: ACTUAL_TRACK_ID, + polyline: { + positions: new Cesium.CallbackProperty(() => trackPositionsRef.current, false), + width: 5, + material: new Cesium.PolylineGlowMaterialProperty({ + glowPower: 0.22, + color: Cesium.Color.fromCssColorString('#f97316').withAlpha(0.95), + }), + clampToGround: true, + }, + }); + } + + viewer.scene.requestRender?.(); + }, [viewerReady, boatData, hasBoatPosition, isSailing, isPreviewing]); return (
- {/* 模型加载提示 */} {modelLoading && (
- 正在加载3D模型... + 正在加载 3D 模型... +
+ )} + + {(hasBoatPosition || hasLoadedModel) && ( +
+ {hasBoatPosition && ( + + )} + {hasLoadedModel && ( + + )}
)} - {/* 地图底部信息栏 */}
- 当前坐标: {boatData?.longitude ? `${boatData.longitude.toFixed(4)}°E, ${boatData.latitude.toFixed(4)}°N` : '--'} + 当前坐标: + {hasBoatPosition + ? ` ${boatData!.longitude.toFixed(4)}°E, ${boatData!.latitude.toFixed(4)}°N` + : ' --'} | - 比例尺: 1:5000 - | - 高程: 3D模式 + 规划航线:青色航点 / 航线 + {isSailing && ( + <> + | + 实际航迹:橙色轨迹线 + + )}
); diff --git a/zlt-web/yingyan/src/pages/client/components/ExecRightPanel/index.less b/zlt-web/yingyan/src/pages/client/components/ExecRightPanel/index.less new file mode 100644 index 00000000..136ffac9 --- /dev/null +++ b/zlt-web/yingyan/src/pages/client/components/ExecRightPanel/index.less @@ -0,0 +1,395 @@ +@bg-sidebar: #0f172a; +@bg-card: #1e293b; +@bg-deep: #0a0f1c; +@border-color: #1e3a5f; +@accent-cyan: #22d3ee; +@accent-orange: #f97316; +@text-primary: #ffffff; +@text-secondary: #94a3b8; +@text-dim: #64748b; +@font-mono: 'JetBrains Mono', 'Courier New', monospace; +@font-sans: 'Inter', -apple-system, sans-serif; + +.panel { + width: 340px; + height: 100%; + background: @bg-sidebar; + border-left: 1px solid @border-color; + padding: 16px; + display: flex; + flex-direction: column; + gap: 14px; + overflow-y: auto; + overflow-x: hidden; + flex-shrink: 0; + + &::-webkit-scrollbar { + width: 4px; + } + + &::-webkit-scrollbar-thumb { + background: rgba(34, 211, 238, 0.22); + border-radius: 999px; + } +} + +.section { + background: linear-gradient(180deg, rgba(30, 41, 59, 0.92), rgba(15, 23, 42, 0.96)); + border: 1px solid @border-color; + border-radius: 14px; + padding: 14px; + display: flex; + flex-direction: column; + gap: 12px; +} + +.sectionHeader { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; +} + +.sectionTitle { + display: inline-flex; + align-items: center; + gap: 8px; + color: @text-primary; + font-size: 13px; + font-weight: 700; + font-family: @font-sans; +} + +.sectionTag { + padding: 4px 8px; + border-radius: 999px; + border: 1px solid rgba(34, 211, 238, 0.28); + background: rgba(34, 211, 238, 0.08); + color: @accent-cyan; + font-size: 10px; + font-family: @font-mono; +} + +.videoCard { + border-radius: 12px; + overflow: hidden; + background: #050a14; + height: 196px; +} + +.videoPlaceholder { + min-height: 196px; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 8px; + color: @text-secondary; + background: + radial-gradient(circle at top, rgba(34, 211, 238, 0.10), transparent 52%), + linear-gradient(180deg, rgba(7, 11, 21, 0.96), rgba(4, 8, 15, 0.98)); +} + +.placeholderIcon { + font-size: 26px; + color: @accent-cyan; +} + +.placeholderTitle { + font-size: 13px; + font-weight: 700; + color: @text-primary; +} + +.placeholderDesc { + font-size: 11px; + color: @text-dim; + text-align: center; +} + +.mockVideoCard { + position: relative; + width: 100%; + height: 100%; + overflow: hidden; + background: + radial-gradient(circle at 50% 18%, rgba(34, 211, 238, 0.24), transparent 28%), + linear-gradient(180deg, #0a1830 0%, #08111f 38%, #06111a 100%); +} + +.mockVideoGlow { + position: absolute; + inset: -10% -20% auto; + height: 65%; + background: radial-gradient(circle, rgba(34, 211, 238, 0.18), transparent 60%); + pointer-events: none; +} + +.mockVideoScanline { + position: absolute; + inset: 0; + background: + linear-gradient(180deg, transparent 0%, rgba(34, 211, 238, 0.1) 48%, transparent 100%), + repeating-linear-gradient( + 180deg, + rgba(255, 255, 255, 0.02) 0, + rgba(255, 255, 255, 0.02) 2px, + transparent 2px, + transparent 6px + ); + animation: videoSweep 4.2s linear infinite; + pointer-events: none; +} + +.mockVideoHud { + position: absolute; + top: 12px; + left: 12px; + right: 12px; + display: flex; + align-items: center; + justify-content: space-between; + z-index: 2; +} + +.mockVideoBadge, +.mockVideoMeta { + padding: 4px 8px; + border-radius: 999px; + background: rgba(8, 15, 28, 0.68); + border: 1px solid rgba(34, 211, 238, 0.28); + color: @accent-cyan; + font-size: 10px; + font-family: @font-mono; +} + +.mockVideoScene { + position: absolute; + inset: 0; +} + +.mockHorizon { + position: absolute; + left: 0; + right: 0; + top: 42%; + height: 1px; + background: rgba(255, 255, 255, 0.24); + box-shadow: 0 0 14px rgba(34, 211, 238, 0.3); +} + +.mockWave { + position: absolute; + left: -12%; + right: -12%; + bottom: 18%; + height: 44%; + border-radius: 42% 58% 0 0 / 20% 24% 0 0; + background: + linear-gradient(180deg, rgba(34, 211, 238, 0.22), rgba(8, 47, 73, 0.82)), + radial-gradient(circle at 50% 0, rgba(255, 255, 255, 0.18), transparent 45%); + animation: waveFloat 6s ease-in-out infinite; +} + +.mockBoatMarker { + position: absolute; + right: 18px; + bottom: 28px; + display: inline-flex; + align-items: center; + gap: 8px; + padding: 7px 10px; + border-radius: 10px; + background: rgba(8, 15, 28, 0.72); + border: 1px solid rgba(34, 211, 238, 0.28); + color: @text-primary; + font-size: 11px; + font-weight: 600; +} + +.mockBoatDot { + width: 8px; + height: 8px; + border-radius: 50%; + background: @accent-orange; + box-shadow: 0 0 0 5px rgba(249, 115, 22, 0.18); +} + +.mockVideoFooter { + position: absolute; + left: 12px; + right: 12px; + bottom: 12px; + display: flex; + justify-content: space-between; + gap: 8px; + color: @text-secondary; + font-size: 10px; + font-family: @font-mono; + z-index: 2; +} + +.lidarCard { + display: flex; + flex-direction: column; + gap: 12px; +} + +.lidarCanvas { + position: relative; + width: 100%; + height: 220px; + border-radius: 12px; + background: + radial-gradient(circle at center, rgba(34, 211, 238, 0.08), transparent 55%), + linear-gradient(180deg, rgba(6, 12, 24, 0.98), rgba(10, 15, 28, 0.98)); + border: 1px solid rgba(34, 211, 238, 0.16); + overflow: hidden; +} + +.lidarSvg { + width: 100%; + height: 100%; +} + +.lidarRing { + fill: none; + stroke: rgba(148, 163, 184, 0.18); + stroke-width: 1; +} + +.lidarAxis { + stroke: rgba(148, 163, 184, 0.14); + stroke-width: 1; +} + +.lidarPoint { + fill: @accent-orange; + opacity: 0.92; +} + +.lidarSweep { + stroke: rgba(34, 211, 238, 0.58); + stroke-width: 1.5; + stroke-linecap: round; + filter: drop-shadow(0 0 6px rgba(34, 211, 238, 0.45)); +} + +.lidarEmpty { + position: absolute; + inset: 0; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 6px; + color: @text-secondary; + font-size: 12px; +} + +.lidarMetrics { + display: flex; + flex-direction: column; + gap: 10px; +} + +.metricItem, +.metricMini { + background: rgba(10, 15, 28, 0.82); + border: 1px solid rgba(30, 58, 95, 0.7); + border-radius: 10px; + padding: 10px 12px; + display: flex; + flex-direction: column; + gap: 4px; +} + +.metricRow { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 8px; +} + +.metricLabel { + font-size: 10px; + color: @text-dim; + font-family: @font-sans; +} + +.metricValue { + font-size: 14px; + color: @text-primary; + font-family: @font-mono; + font-weight: 700; +} + +.summaryGrid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 10px; +} + +.summaryCard { + min-height: 86px; + border-radius: 12px; + border: 1px solid rgba(30, 58, 95, 0.78); + background: rgba(10, 15, 28, 0.84); + padding: 12px; + display: flex; + flex-direction: column; + gap: 6px; +} + +.summaryIcon { + font-size: 16px; +} + +.summaryLabel { + color: @text-dim; + font-size: 10px; + font-family: @font-sans; +} + +.summaryValue { + color: @text-primary; + font-size: 13px; + line-height: 1.4; + font-family: @font-mono; + font-weight: 700; + word-break: break-word; +} + +@media (max-width: 1366px) { + .panel { + width: 300px; + padding: 12px; + } + + .videoCard { + height: 168px; + } + + .lidarCanvas { + height: 190px; + } +} + +@keyframes videoSweep { + 0% { + transform: translateY(-100%); + } + + 100% { + transform: translateY(100%); + } +} + +@keyframes waveFloat { + 0%, 100% { + transform: translateY(0) scaleX(1); + } + + 50% { + transform: translateY(5px) scaleX(1.03); + } +} diff --git a/zlt-web/yingyan/src/pages/client/components/ExecRightPanel/index.tsx b/zlt-web/yingyan/src/pages/client/components/ExecRightPanel/index.tsx new file mode 100644 index 00000000..ddeb31ee --- /dev/null +++ b/zlt-web/yingyan/src/pages/client/components/ExecRightPanel/index.tsx @@ -0,0 +1,300 @@ +import React, { useEffect, useMemo, useState } from 'react'; +import { + VideoCameraOutlined, + RadarChartOutlined, + EnvironmentOutlined, + ThunderboltOutlined, + WifiOutlined, +} from '@ant-design/icons'; +import WhepPlayer from '@/pages/map3d/components/MapContainer/3d/BottomPanel/WhepPlayer'; +import type { BoatRouteListVO, BoatTelemetryData } from '@/types/boatRoute'; +import styles from './index.less'; + +interface ExecRightPanelProps { + deviceInfo: any; + boatData: BoatTelemetryData | null; + activeRouteInfo: BoatRouteListVO | null; + sseConnected: boolean; + videoStreamUrl?: string; + isPreviewing?: boolean; +} + +interface LidarSample { + angle: number; + distance: number; +} + +const clampNumber = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value)); + +const extractLidarSamples = (deviceInfo: any, boatData: BoatTelemetryData | null): LidarSample[] => { + const raw = + (boatData as any)?.lidarSamples || + (boatData as any)?.lidarPoints || + (boatData as any)?.lidarDistances || + (deviceInfo as any)?.lidarSamples || + (deviceInfo as any)?.lidarPoints || + (deviceInfo as any)?.lidarDistances || + []; + + if (!Array.isArray(raw) || raw.length === 0) return []; + + if (typeof raw[0] === 'number') { + return raw.map((distance: number, index: number) => ({ + angle: (index / raw.length) * 360, + distance: Number(distance) || 0, + })); + } + + return raw + .map((item: any, index: number) => ({ + angle: Number(item?.angle ?? item?.deg ?? item?.theta ?? (index / raw.length) * 360), + distance: Number(item?.distance ?? item?.range ?? item?.value ?? 0), + })) + .filter((item) => Number.isFinite(item.angle) && Number.isFinite(item.distance)); +}; + +const createMockLidarSamples = (phase: number): LidarSample[] => ( + Array.from({ length: 72 }, (_, index) => { + const angle = index * 5; + const wave = Math.sin((angle + phase * 28) * Math.PI / 180); + const ripple = Math.cos((angle * 2 + phase * 36) * Math.PI / 180); + const bump = (index % 9 === 0 ? 4.5 : 0) + (index % 13 === 0 ? 2.6 : 0); + const distance = clampNumber(16 + wave * 6 + ripple * 3 + bump, 3.6, 31); + return { angle, distance }; + }) +); + +const ExecRightPanel: React.FC = ({ + deviceInfo, + boatData, + activeRouteInfo, + sseConnected, + videoStreamUrl, + isPreviewing = false, +}) => { + const [mockPhase, setMockPhase] = useState(0); + + useEffect(() => { + if (!isPreviewing) return undefined; + const timer = window.setInterval(() => { + setMockPhase((value) => (value + 1) % 360); + }, 900); + return () => window.clearInterval(timer); + }, [isPreviewing]); + + const realLidarSamples = useMemo(() => extractLidarSamples(deviceInfo, boatData), [deviceInfo, boatData]); + const lidarSamples = useMemo( + () => (isPreviewing ? createMockLidarSamples(mockPhase) : realLidarSamples), + [isPreviewing, mockPhase, realLidarSamples], + ); + const hasBoatPosition = Number.isFinite(boatData?.longitude) && Number.isFinite(boatData?.latitude); + + const lidarMetrics = useMemo(() => { + if (!lidarSamples.length) { + return { + minDistance: null, + frontDistance: null, + leftDistance: null, + rightDistance: null, + }; + } + + const pickClosest = (targetAngle: number) => { + const matched = lidarSamples.reduce((best, current) => { + const delta = Math.abs((((current.angle - targetAngle) % 360) + 540) % 360 - 180); + return delta < best.delta ? { delta, distance: current.distance } : best; + }, { delta: Number.POSITIVE_INFINITY, distance: 0 }); + return matched.distance; + }; + + return { + minDistance: Math.min(...lidarSamples.map((item) => item.distance)), + frontDistance: pickClosest(0), + leftDistance: pickClosest(270), + rightDistance: pickClosest(90), + }; + }, [lidarSamples]); + + const lidarPoints = useMemo(() => { + if (!lidarSamples.length) return []; + const maxDistance = Math.max(10, ...lidarSamples.map((item) => item.distance)); + const radius = 88; + + return lidarSamples.slice(0, 72).map((sample) => { + const normalized = clampNumber(sample.distance / maxDistance, 0.08, 1); + const actualRadius = normalized * radius; + const angleRad = (sample.angle - 90) * Math.PI / 180; + return { + x: 110 + Math.cos(angleRad) * actualRadius, + y: 110 + Math.sin(angleRad) * actualRadius, + }; + }); + }, [lidarSamples]); + + const statusItems = [ + { + label: '设备状态', + value: isPreviewing ? '模拟预览' : (sseConnected ? '在线' : '离线'), + icon: , + accent: isPreviewing ? '#22d3ee' : (sseConnected ? '#10b981' : '#ef4444'), + }, + { + label: '剩余电量', + value: `${boatData?.battery ?? (isPreviewing ? 86 : 0)}%`, + icon: , + accent: (boatData?.battery ?? 86) > 20 ? '#22d3ee' : '#f59e0b', + }, + { + label: '当前位置', + value: hasBoatPosition ? `${boatData!.longitude.toFixed(4)}, ${boatData!.latitude.toFixed(4)}` : '--', + icon: , + accent: '#94a3b8', + }, + ]; + + const formatMeters = (distance: number | null) => (distance == null ? '--' : `${distance.toFixed(distance >= 10 ? 0 : 1)} m`); + + return ( +
+
+
+ + + 视频回传 + + + {isPreviewing ? '模拟流' : (videoStreamUrl ? '实时流' : '未接入')} + +
+
+ {isPreviewing ? ( +
+
+
+
+ SIM CAM + 1080P / 25 FPS +
+
+
+
+
+ + 航线预览目标 +
+
+
+ 模拟海况:2级 + 光照:良好 + 延迟:42ms +
+
+ ) : videoStreamUrl ? ( + + ) : ( +
+ +
暂无视频流
+
设备未配置 `videoStreamUrl` 或 `whepUrl`
+
+ )} +
+
+ +
+
+ + + 激光雷达 + + + {isPreviewing ? `模拟 ${lidarSamples.length} 点` : (lidarSamples.length > 0 ? `${lidarSamples.length} 点` : '未接入')} + +
+ +
+
+ + + + + + + + {lidarPoints.map((point, index) => ( + + ))} + + {lidarPoints.length === 0 && ( +
+ + 暂无激光雷达数据 +
+ )} +
+ +
+
+ 最近障碍距离 + {formatMeters(lidarMetrics.minDistance)} +
+
+
+ 前方 + {formatMeters(lidarMetrics.frontDistance)} +
+
+ 左侧 + {formatMeters(lidarMetrics.leftDistance)} +
+
+ 右侧 + {formatMeters(lidarMetrics.rightDistance)} +
+
+
+
+
+ +
+
+ 执行摘要 + {activeRouteInfo?.routeName || '未选择航线'} +
+
+ {statusItems.map((item) => ( +
+
{item.icon}
+
{item.label}
+
{item.value}
+
+ ))} +
+
规划总长
+
+ {activeRouteInfo ? `${(activeRouteInfo.totalDistance / 1000).toFixed(2)} km` : '--'} +
+
+
+
预计时长
+
{activeRouteInfo?.totalDurationStr || '--'}
+
+
+
航向 / 速度
+
+ {boatData ? `${Math.round(boatData.heading || 0)}° / ${boatData.speed?.toFixed(1) || '0.0'} m/s` : '--'} +
+
+
+
+
+ ); +}; + +export default ExecRightPanel; diff --git a/zlt-web/yingyan/src/pages/client/components/LeftPanel/index.tsx b/zlt-web/yingyan/src/pages/client/components/LeftPanel/index.tsx index a76e9064..f7dc1b98 100644 --- a/zlt-web/yingyan/src/pages/client/components/LeftPanel/index.tsx +++ b/zlt-web/yingyan/src/pages/client/components/LeftPanel/index.tsx @@ -27,13 +27,11 @@ interface LeftPanelProps { sailingLoading: boolean; } -/** 格式化距离 */ const formatDistance = (meters?: number) => { if (!meters || meters <= 0) return null; return meters >= 1000 ? `${(meters / 1000).toFixed(1)}km` : `${Math.round(meters)}m`; }; -/** 格式化时间(秒 → "XX分钟") */ const formatDuration = (seconds?: number) => { if (!seconds || seconds <= 0) return null; const min = Math.round(seconds / 60); @@ -55,10 +53,10 @@ const LeftPanel: React.FC = ({ }) => { const battery = boatData?.battery ?? 0; const isOnline = sseConnected; + const hasBoatPosition = Number.isFinite(boatData?.longitude) && Number.isFinite(boatData?.latitude); return (
- {/* ========== 设备状态卡片 ========== */}
设备状态 @@ -74,7 +72,7 @@ const LeftPanel: React.FC = ({ GPS 信号 - {boatData?.longitude ? '强' : '弱'} + {hasBoatPosition ? '已定位' : '未定位'}
@@ -84,8 +82,8 @@ const LeftPanel: React.FC = ({ 当前位置 - {boatData?.longitude - ? `${boatData.longitude.toFixed(2)}°E ${boatData.latitude.toFixed(2)}°N` + {hasBoatPosition + ? `${boatData!.longitude.toFixed(4)}°E ${boatData!.latitude.toFixed(4)}°N` : '--'}
@@ -131,12 +129,10 @@ const LeftPanel: React.FC = ({
- {/* ========== 分隔线 ========== */}
- {/* ========== 航线区域 ========== */}
- 浏览线路 + 航线列表 {routes.length} 条航线 @@ -172,11 +168,13 @@ const LeftPanel: React.FC = ({
就绪
+
- {wpCount}个航点{distance ? ` · 约${distance}` : ''}{duration ? ` · 预计${duration}` : ''} + {wpCount} 个航点 + {distance ? ` · 约 ${distance}` : ''} + {duration ? ` · 预计 ${duration}` : ''}
- {/* 选中时显示操作按钮 */} {isSelected && (
e.stopPropagation()}>
)} + {routes.length > 2 &&
上下滑动查看更多航线
}
diff --git a/zlt-web/yingyan/src/pages/client/hooks/useRoutePreview.ts b/zlt-web/yingyan/src/pages/client/hooks/useRoutePreview.ts index 4295ebbc..ca1ea7ef 100644 --- a/zlt-web/yingyan/src/pages/client/hooks/useRoutePreview.ts +++ b/zlt-web/yingyan/src/pages/client/hooks/useRoutePreview.ts @@ -1,39 +1,71 @@ -/** - * 航线第一视角预览 Hook - * 从鹰眼 RouteEditor 中提取的预览动画逻辑,用于客户端页面航线预览 - */ import { useState, useRef, useCallback, useEffect } from 'react'; import type { MessageInstance } from 'antd/es/message/interface'; import type { BoatWaypointDTO } from '@/types/boatRoute'; +import type { RouteSurfaceGeometry } from '@/pages/map3d/components/RouteEditor/hooks/useCesiumRouteLibraryRenderer'; export interface UseRoutePreviewOptions { viewerRef: React.RefObject; messageApi?: MessageInstance; + getRouteSurfaceGeometry?: (routeId: string) => RouteSurfaceGeometry | null; } export interface UseRoutePreviewReturn { isPreviewing: boolean; - startPreview: (waypoints: BoatWaypointDTO[], speed?: number) => Promise; + startPreview: (waypoints: BoatWaypointDTO[], speed?: number, routeId?: string) => Promise; stopPreview: () => void; } -export function useRoutePreview({ viewerRef, messageApi }: UseRoutePreviewOptions): UseRoutePreviewReturn { +const MODEL_HEADING_OFFSET = -Math.PI / 2; +const ROUTE_HEIGHT_OFFSET = 0.8; +const BOAT_HEIGHT_OFFSET = 0.35; +const TURN_HOLD_MS = 500; +const TURN_ROTATE_MS = 650; +const TURN_ANGLE_THRESHOLD_DEG = 12; + +export function useRoutePreview({ + viewerRef, + messageApi, + getRouteSurfaceGeometry, +}: UseRoutePreviewOptions): UseRoutePreviewReturn { const [isPreviewing, setIsPreviewing] = useState(false); const previewAnimationRef = useRef(null); const savedCameraStateRef = useRef(null); - const previewBoatPartsRef = useRef<{ boat?: any } | null>(null); - const previewRouteEntitiesRef = useRef([]); - const previewTravelDistanceRef = useRef(0); + const previewBoatEntityRef = useRef(null); + const previewEntitiesRef = useRef([]); + const escHandlerRef = useRef<((e: KeyboardEvent) => void) | null>(null); const getCesium = useCallback(() => (window as any).Cesium, []); - // GLB 模型自身朝向补偿(模型建模方向与 Cesium 北向的偏差) - const MODEL_HEADING_OFFSET = -Math.PI / 2; - const PREVIEW_ROUTE_HEIGHT_OFFSET = 0.05; - const PREVIEW_BOAT_HEIGHT_OFFSET = 0.14; - const PREVIEW_ROUTE_BOAT_CLEARANCE = 0; // 设置为 0,取消空隙,保证所有航点完全连线 - // 计算两点间航向角 - const calculateHeading = useCallback((from: { longitude: number; latitude: number }, to: { longitude: number; latitude: number }) => { + const requestRender = useCallback(() => { + const viewer = viewerRef?.current; + if (!viewer || viewer.isDestroyed?.()) return; + try { + viewer.scene?.requestRender?.(); + } catch { + // ignore + } + }, [viewerRef]); + + const setStaticRouteEntitiesVisible = useCallback((visible: boolean) => { + const viewer = viewerRef?.current; + if (!viewer || viewer.isDestroyed?.() || !viewer.entities) return; + + viewer.entities.values.forEach((entity: any) => { + const type = entity.properties?.type?.getValue?.(); + if ( + type === 'route-library-path' + || type === 'route-library-point' + || type === 'route-library-waypoint' + ) { + entity.show = visible; + } + }); + }, [viewerRef]); + + const calculateHeading = useCallback(( + from: { longitude: number; latitude: number }, + to: { longitude: number; latitude: number }, + ) => { const dLon = (to.longitude - from.longitude) * Math.PI / 180; const lat1 = from.latitude * Math.PI / 180; const lat2 = to.latitude * Math.PI / 180; @@ -43,7 +75,6 @@ export function useRoutePreview({ viewerRef, messageApi }: UseRoutePreviewOption return (bearing + 360) % 360; }, []); - // 停止预览 const stopPreview = useCallback(() => { setIsPreviewing(false); @@ -51,506 +82,44 @@ export function useRoutePreview({ viewerRef, messageApi }: UseRoutePreviewOption cancelAnimationFrame(previewAnimationRef.current); previewAnimationRef.current = null; } - if ((previewAnimationRef as any).escHandler) { - window.removeEventListener('keydown', (previewAnimationRef as any).escHandler); - (previewAnimationRef as any).escHandler = null; + + if (escHandlerRef.current) { + window.removeEventListener('keydown', escHandlerRef.current); + escHandlerRef.current = null; } - // 清理船只实体 - if (previewBoatPartsRef.current) { - try { - const viewer = viewerRef?.current; - if (viewer && !viewer.isDestroyed?.()) { - const { boat } = previewBoatPartsRef.current; - if (boat) viewer.entities.remove(boat); - } - } catch { /* ignore */ } finally { - previewBoatPartsRef.current = null; - } - } - - // 清理预览航线实体 - if (previewRouteEntitiesRef.current.length > 0) { - try { - const viewer = viewerRef?.current; - if (viewer && !viewer.isDestroyed?.()) { - previewRouteEntitiesRef.current.forEach((entity) => { - if (entity) viewer.entities.remove(entity); - }); - } - } catch { /* ignore */ } finally { - previewRouteEntitiesRef.current = []; - } - } - previewTravelDistanceRef.current = 0; - - // 恢复主视图中的静态航线实体 - if (viewerRef?.current && !viewerRef.current.isDestroyed?.() && viewerRef.current.entities) { - viewerRef.current.entities.values.forEach((entity: any) => { - if (entity.properties && entity.properties.type && entity.properties.type.getValue() === 'route-library-path') { - entity.show = true; - } - }); - } - - // 恢复相机 - if (savedCameraStateRef.current && viewerRef?.current) { - const viewer = viewerRef.current; - const Cesium = getCesium(); - try { if (Cesium?.Matrix4) viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY); } catch { /* ignore */ } - viewer.camera.setView({ - destination: savedCameraStateRef.current.position, - orientation: { - heading: savedCameraStateRef.current.heading, - pitch: savedCameraStateRef.current.pitch, - roll: savedCameraStateRef.current.roll, - }, - }); - savedCameraStateRef.current = null; - } - }, [viewerRef, getCesium]); - - // 构建预览折线(密集化 + 贴模型表面) - const buildPreviewPolyline = useCallback(async (points: BoatWaypointDTO[]) => { const viewer = viewerRef?.current; - const Cesium = getCesium(); - if (!viewer || !Cesium || viewer.isDestroyed?.()) return []; - if (!Array.isArray(points) || points.length < 2) return []; - - const applyOffset = (cartesian: any) => { + if (viewer && !viewer.isDestroyed?.()) { try { - const carto = Cesium.Cartographic.fromCartesian(cartesian); - carto.height = (Number(carto.height) || 0) + PREVIEW_ROUTE_HEIGHT_OFFSET; - return Cesium.Cartesian3.fromRadians(carto.longitude, carto.latitude, carto.height); - } catch { return cartesian; } - }; - - // 密集化航点 - const cartos: any[] = []; - let total = 0; - const maxTotal = 500; - for (let i = 0; i < points.length - 1; i++) { - const a = points[i], b = points[i + 1]; - const ca = Cesium.Cartographic.fromDegrees(a.longitude, a.latitude, 300); - const cb = Cesium.Cartographic.fromDegrees(b.longitude, b.latitude, 300); - const geodesic = new Cesium.EllipsoidGeodesic(ca, cb); - const dist = Number(geodesic.surfaceDistance) || 0; - const segments = Math.max(2, Math.min(60, Math.ceil(dist / 10))); - for (let s = 0; s <= segments; s++) { - if (i > 0 && s === 0) continue; - if (total >= maxTotal) break; - const c = geodesic.interpolateUsingFraction(segments === 0 ? 0 : s / segments); - c.height = 300; - cartos.push(c); - total++; - } - if (total >= maxTotal) break; - } - - if (cartos.length < 2) { - return points.map((p) => Cesium.Cartesian3.fromDegrees(p.longitude, p.latitude, 0)).map(applyOffset); - } - - const above = cartos.map((c: any) => Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, c.height || 300)); - const ground = cartos.map((c: any) => Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, 0)); - const clampFn = viewer.scene?.clampToHeightMostDetailed; - if (typeof clampFn !== 'function') return ground.map(applyOffset); - - try { - const clamped = await clampFn.call(viewer.scene, above); - const merged = (clamped || []).map((p: any, idx: number) => p || ground[idx]); - const okCount = (clamped || []).filter(Boolean).length; - if (okCount < 2) return ground.map(applyOffset); - return merged.map(applyOffset); - } catch { - return ground.map(applyOffset); - } - }, [viewerRef, getCesium]); - - // 开始预览 - const startPreview = useCallback(async (waypoints: BoatWaypointDTO[], speed: number = 2) => { - const viewer = viewerRef?.current; - const Cesium = getCesium(); - if (!viewer || !Cesium || viewer.isDestroyed?.()) return; - if (!waypoints || waypoints.length < 2) { - messageApi?.warning('至少需要2个航点才能预览'); - return; - } - - if (isPreviewing) stopPreview(); - - const rawPolylinePositions = await buildPreviewPolyline(waypoints); - const polylinePositions = Array.isArray(rawPolylinePositions) ? rawPolylinePositions.filter(Boolean) : []; - if (polylinePositions.length < 2) { - messageApi?.warning('模型瓦片加载中,请稍后再试预览'); - return; - } - - // 清理旧船只 - if (previewBoatPartsRef.current) { - try { - const { boat } = previewBoatPartsRef.current; - if (boat) viewer.entities.remove(boat); - } catch { /* ignore */ } finally { - previewBoatPartsRef.current = null; - } - } - - // 保存相机 - savedCameraStateRef.current = { - position: viewer.camera.position.clone(), - heading: viewer.camera.heading, - pitch: viewer.camera.pitch, - roll: viewer.camera.roll, - }; - - setIsPreviewing(true); - messageApi?.info('开始航线预览,按ESC退出'); - - // 隐藏主视图中的静态航线实体 - if (viewer.entities) { - viewer.entities.values.forEach((entity: any) => { - if (entity.properties && entity.properties.type && entity.properties.type.getValue() === 'route-library-path') { - entity.show = false; + if (previewBoatEntityRef.current) { + viewer.entities.remove(previewBoatEntityRef.current); } - }); - } - - // 添加可见的预览航线实体(确保第一视角能看到整条航线) - const chaseRange = 22; - const chasePitch = -20; - const ellipsoid = Cesium.Ellipsoid?.WGS84; - - // 计算累积距离 - const distances: number[] = [0]; - for (let i = 1; i < polylinePositions.length; i++) { - distances[i] = distances[i - 1] + Cesium.Cartesian3.distance(polylinePositions[i - 1], polylinePositions[i]); - } - const totalDist = distances[distances.length - 1] || 0; - if (totalDist <= 1) { - messageApi?.warning('航线过短,无法预览'); - setIsPreviewing(false); - return; - } - - // Up方向偏移工具 - const scratchEnu = new Cesium.Matrix4(); - const scratchLocalOffset = new Cesium.Cartesian3(); - const offsetUp = (origin: any, upMeters: number) => { - try { - if (!Cesium.Transforms?.eastNorthUpToFixedFrame || !Cesium.Matrix4?.multiplyByPoint) return origin; - const enu = Cesium.Transforms.eastNorthUpToFixedFrame(origin, ellipsoid, scratchEnu); - scratchLocalOffset.x = 0; scratchLocalOffset.y = 0; scratchLocalOffset.z = upMeters; - return Cesium.Matrix4.multiplyByPoint(enu, scratchLocalOffset, new Cesium.Cartesian3()); - } catch { return origin; } - }; - - // 创建船只实体(GLB 模型) - try { - const firstPos0 = polylinePositions[0]; - const boatAboveRoute = PREVIEW_BOAT_HEIGHT_OFFSET; - const firstPos = offsetUp(firstPos0, boatAboveRoute); - const initialOrientation = Cesium.Transforms?.headingPitchRollQuaternion - ? Cesium.Transforms.headingPitchRollQuaternion(firstPos, new Cesium.HeadingPitchRoll(MODEL_HEADING_OFFSET, 0, 0)) - : undefined; - - const boat = viewer.entities.add({ - position: firstPos, - orientation: initialOrientation, - model: { - uri: `${process.env.CESIUM_BASE_URL || '/'}chuan-model.glb`, - scale: 0.001, - minimumPixelSize: 64, - maximumScale: 200, - runAnimations: true, - colorBlendMode: Cesium.ColorBlendMode.HIGHLIGHT, - color: Cesium.Color.WHITE, - silhouetteSize: 0, - }, - }); - - previewBoatPartsRef.current = { boat }; - (previewBoatPartsRef.current as any).boatAboveRoute = boatAboveRoute; - } catch (e) { - console.warn('创建预览船只实体失败:', e); - } - - // 二分查找距离索引 - const findIndexByDistance = (d: number) => { - let lo = 0, hi = distances.length - 1; - while (lo < hi) { const mid = Math.floor((lo + hi) / 2); if (distances[mid] < d) lo = mid + 1; else hi = mid; } - return Math.max(1, lo); - }; - - const scratchPosCur = new Cesium.Cartesian3(); - const scratchPosA = new Cesium.Cartesian3(); - const scratchPosB = new Cesium.Cartesian3(); - const scratchCartoCur = new Cesium.Cartographic(); - const scratchCartoA = new Cesium.Cartographic(); - const scratchCartoB = new Cesium.Cartographic(); - - const fillSampleAtDistance = (d: number, outPos: any, outCarto: any) => { - const dd = Math.min(totalDist, Math.max(0, d)); - const idx = findIndexByDistance(dd); - const prevD = distances[idx - 1] || 0; - const nextD = distances[idx] || prevD + 1; - const frac = Math.min(1, Math.max(0, (dd - prevD) / Math.max(1e-6, nextD - prevD))); - Cesium.Cartesian3.lerp(polylinePositions[idx - 1], polylinePositions[idx], frac, outPos); - try { - Cesium.Cartographic.fromCartesian(outPos, ellipsoid || undefined, outCarto); } catch { - const c = Cesium.Cartographic.fromCartesian(outPos); - outCarto.longitude = c.longitude; outCarto.latitude = c.latitude; outCarto.height = c.height; + // ignore } - }; + previewBoatEntityRef.current = null; - // 拐点检测 - const samplePositionAtDistance = (d: number) => { - const pos = new Cesium.Cartesian3(); - const carto = new Cesium.Cartographic(); - fillSampleAtDistance(d, pos, carto); - return pos; - }; - - const dedupePositions = (positions: any[]) => { - const result: any[] = []; - positions.forEach((pos) => { - if (!pos) return; - const prev = result[result.length - 1]; - if (!prev || Cesium.Cartesian3.distance(prev, pos) > 0.01) { - result.push(pos); + previewEntitiesRef.current.forEach((entity) => { + try { + if (entity) viewer.entities.remove(entity); + } catch { + // ignore } }); - return result; - }; + previewEntitiesRef.current = []; - const buildSegmentPositions = (startDistance: number, endDistance: number) => { - const clampedStart = Math.max(0, Math.min(totalDist, startDistance)); - const clampedEnd = Math.max(0, Math.min(totalDist, endDistance)); - if (clampedEnd - clampedStart <= 0.05) return []; + setStaticRouteEntitiesVisible(true); - const positions: any[] = []; - positions.push(clampedStart <= 0.01 ? polylinePositions[0] : samplePositionAtDistance(clampedStart)); - - const startIdx = Math.max(1, findIndexByDistance(clampedStart)); - const endIdx = Math.min(polylinePositions.length - 1, findIndexByDistance(clampedEnd)); - for (let i = startIdx; i < endIdx; i++) { - positions.push(polylinePositions[i]); - } - - positions.push( - clampedEnd >= totalDist - 0.01 - ? polylinePositions[polylinePositions.length - 1] - : samplePositionAtDistance(clampedEnd) - ); - - return dedupePositions(positions); - }; - - previewTravelDistanceRef.current = 0; - - try { - const polylineStyle = { - width: 6, - material: new Cesium.PolylineGlowMaterialProperty({ - glowPower: 0.4, - color: Cesium.Color.fromCssColorString('#22d3ee').withAlpha(0.9), - }), - depthFailMaterial: new Cesium.PolylineGlowMaterialProperty({ - glowPower: 0.4, - color: Cesium.Color.fromCssColorString('#22d3ee').withAlpha(0.9), - }), - clampToGround: false, - }; - const routeBeforeEntity = viewer.entities.add({ - polyline: { - ...polylineStyle, - positions: new Cesium.CallbackProperty( - () => buildSegmentPositions(0, previewTravelDistanceRef.current - PREVIEW_ROUTE_BOAT_CLEARANCE), - false, - ), - }, - }); - - const routeAfterEntity = viewer.entities.add({ - polyline: { - ...polylineStyle, - positions: new Cesium.CallbackProperty( - () => buildSegmentPositions(previewTravelDistanceRef.current + PREVIEW_ROUTE_BOAT_CLEARANCE, totalDist), - false, - ), - }, - }); - - previewRouteEntitiesRef.current = [routeBeforeEntity, routeAfterEntity]; - } catch { /* ignore */ } - - const turnAngleThresholdDeg = 12; - const turnHoldMs = 200; - const turnRotateMs = 650; - const normalizeAngleDeg = (deg: number) => ((deg % 360) + 360) % 360; - const shortestDeltaDeg = (fromDeg: number, toDeg: number) => { - let delta = normalizeAngleDeg(toDeg) - normalizeAngleDeg(fromDeg); - if (delta > 180) delta -= 360; if (delta < -180) delta += 360; - return delta; - }; - const lerpHeadingDeg = (fromDeg: number, toDeg: number, f: number) => { - return normalizeAngleDeg(fromDeg + shortestDeltaDeg(fromDeg, toDeg) * Math.min(1, Math.max(0, f))); - }; - - const cornerInfos: Array<{ distance: number; fromHeading: number; toHeading: number }> = []; - try { - for (let i = 1; i < polylinePositions.length - 1; i++) { - const cPrev = new Cesium.Cartographic(), c = new Cesium.Cartographic(), cNext = new Cesium.Cartographic(); + if (savedCameraStateRef.current) { + const Cesium = getCesium(); try { - Cesium.Cartographic.fromCartesian(polylinePositions[i - 1], ellipsoid, cPrev); - Cesium.Cartographic.fromCartesian(polylinePositions[i], ellipsoid, c); - Cesium.Cartographic.fromCartesian(polylinePositions[i + 1], ellipsoid, cNext); - } catch { continue; } - const h1 = calculateHeading( - { longitude: Cesium.Math.toDegrees(cPrev.longitude), latitude: Cesium.Math.toDegrees(cPrev.latitude) }, - { longitude: Cesium.Math.toDegrees(c.longitude), latitude: Cesium.Math.toDegrees(c.latitude) } - ); - const h2 = calculateHeading( - { longitude: Cesium.Math.toDegrees(c.longitude), latitude: Cesium.Math.toDegrees(c.latitude) }, - { longitude: Cesium.Math.toDegrees(cNext.longitude), latitude: Cesium.Math.toDegrees(cNext.latitude) } - ); - if (Math.abs(shortestDeltaDeg(h1, h2)) >= turnAngleThresholdDeg) { - cornerInfos.push({ distance: distances[i], fromHeading: h1, toHeading: h2 }); - } - } - } catch { /* ignore */ } - - let lastT = 0, traveled = 0; - let mode: 'move' | 'turn' = 'move'; - let cornerPtr = 0, turnStartT = 0, turnFromHeading = 0, turnToHeading = 0, turnDistance = 0; - - const animatePreview = (t: number) => { - if (!lastT) lastT = t; - const dt = Math.max(0, (t - lastT) / 1000); - lastT = t; - - if (mode === 'move') { - traveled += dt * speed; - if (cornerPtr < cornerInfos.length && traveled >= cornerInfos[cornerPtr].distance) { - traveled = cornerInfos[cornerPtr].distance; - mode = 'turn'; turnStartT = t; - turnFromHeading = cornerInfos[cornerPtr].fromHeading; - turnToHeading = cornerInfos[cornerPtr].toHeading; - turnDistance = cornerInfos[cornerPtr].distance; - } - } else { - traveled = turnDistance; - if (t - turnStartT >= turnHoldMs + turnRotateMs) { - mode = 'move'; cornerPtr++; - } - } - - previewTravelDistanceRef.current = traveled; - - if (traveled >= totalDist) { - stopPreview(); - messageApi?.success('航线预览完成'); - return; - } - - fillSampleAtDistance(traveled, scratchPosCur, scratchCartoCur); - - let headingDeg = 0; - if (mode === 'turn') { - const elapsed = t - turnStartT; - headingDeg = elapsed <= turnHoldMs - ? turnFromHeading - : lerpHeadingDeg(turnFromHeading, turnToHeading, (elapsed - turnHoldMs) / Math.max(1, turnRotateMs)); - } else { - const delta = Math.max(0.6, Math.min(2.5, speed * 0.35)); - fillSampleAtDistance(traveled - delta, scratchPosA, scratchCartoA); - fillSampleAtDistance(traveled + delta, scratchPosB, scratchCartoB); - headingDeg = calculateHeading( - { longitude: Cesium.Math.toDegrees(scratchCartoA.longitude), latitude: Cesium.Math.toDegrees(scratchCartoA.latitude) }, - { longitude: Cesium.Math.toDegrees(scratchCartoB.longitude), latitude: Cesium.Math.toDegrees(scratchCartoB.latitude) } - ); - } - const headingRad = Cesium.Math.toRadians(headingDeg); - - // 更新船只位置 - try { - if (previewBoatPartsRef.current) { - const boatAboveRoute = Number((previewBoatPartsRef.current as any).boatAboveRoute) || PREVIEW_BOAT_HEIGHT_OFFSET; - const basePos = offsetUp(scratchPosCur, boatAboveRoute); - const orientation = Cesium.Transforms?.headingPitchRollQuaternion - ? Cesium.Transforms.headingPitchRollQuaternion(basePos, new Cesium.HeadingPitchRoll(headingRad + MODEL_HEADING_OFFSET, 0, 0)) - : undefined; - const { boat } = previewBoatPartsRef.current; - if (boat) { - boat.position = basePos; - if (orientation) boat.orientation = orientation; + if (Cesium?.Matrix4) { + viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY); } + } catch { + // ignore } - } catch { /* ignore */ } - // 追踪相机 - try { - const target = offsetUp(scratchPosCur, 0.8); - viewer.camera.lookAt(target, new Cesium.HeadingPitchRange(headingRad, Cesium.Math.toRadians(chasePitch), chaseRange)); - } catch { - viewer.camera.setView({ - destination: Cesium.Cartesian3.fromRadians(scratchCartoCur.longitude, scratchCartoCur.latitude, (Number(scratchCartoCur.height) || 0) + 10), - orientation: { heading: headingRad, pitch: Cesium.Math.toRadians(-10), roll: 0 }, - }); - } - - try { viewer.scene?.requestRender?.(); } catch { /* ignore */ } - previewAnimationRef.current = requestAnimationFrame(animatePreview); - }; - - // 先请求一次渲染再启动动画 - try { viewer.scene?.requestRender?.(); } catch { /* ignore */ } - setTimeout(() => { - previewAnimationRef.current = requestAnimationFrame(animatePreview); - }, 120); - - // ESC退出 - const handleEsc = (e: KeyboardEvent) => { if (e.key === 'Escape') stopPreview(); }; - window.addEventListener('keydown', handleEsc); - (previewAnimationRef as any).escHandler = handleEsc; - }, [viewerRef, getCesium, isPreviewing, stopPreview, calculateHeading, buildPreviewPolyline, messageApi]); - - // 组件卸载清理 - useEffect(() => { - return () => { - if (previewAnimationRef.current) cancelAnimationFrame(previewAnimationRef.current); - if ((previewAnimationRef as any).escHandler) { - window.removeEventListener('keydown', (previewAnimationRef as any).escHandler); - } - if (previewBoatPartsRef.current) { - try { - const viewer = viewerRef?.current; - if (viewer && !viewer.isDestroyed?.()) { - const { boat } = previewBoatPartsRef.current; - if (boat) viewer.entities.remove(boat); - } - } catch { /* ignore */ } finally { - previewBoatPartsRef.current = null; - } - } - if (previewRouteEntitiesRef.current.length > 0) { - try { - const viewer = viewerRef?.current; - if (viewer && !viewer.isDestroyed?.()) { - previewRouteEntitiesRef.current.forEach((entity) => { - if (entity) viewer.entities.remove(entity); - }); - } - } catch { /* ignore */ } finally { - previewRouteEntitiesRef.current = []; - } - } - previewTravelDistanceRef.current = 0; - if (savedCameraStateRef.current && viewerRef?.current) { - const viewer = viewerRef.current; - const Cesium = (window as any).Cesium; - try { if (Cesium?.Matrix4) viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY); } catch { /* ignore */ } try { viewer.camera.setView({ destination: savedCameraStateRef.current.position, @@ -560,12 +129,463 @@ export function useRoutePreview({ viewerRef, messageApi }: UseRoutePreviewOption roll: savedCameraStateRef.current.roll, }, }); - } catch { /* ignore */ } finally { - savedCameraStateRef.current = null; + } catch { + // ignore } + + savedCameraStateRef.current = null; + } + } + + requestRender(); + }, [viewerRef, getCesium, requestRender, setStaticRouteEntitiesVisible]); + + const buildPreviewWaypointPositions = useCallback(async (points: BoatWaypointDTO[]) => { + const viewer = viewerRef?.current; + const Cesium = getCesium(); + if (!viewer || !Cesium || viewer.isDestroyed?.()) return []; + if (!Array.isArray(points) || points.length === 0) return []; + + const applyOffset = (cartesian: any) => { + try { + const cartographic = Cesium.Cartographic.fromCartesian(cartesian); + cartographic.height = (Number(cartographic.height) || 0) + ROUTE_HEIGHT_OFFSET; + return Cesium.Cartesian3.fromRadians( + cartographic.longitude, + cartographic.latitude, + cartographic.height, + ); + } catch { + return cartesian; } }; - }, [viewerRef]); - return { isPreviewing, startPreview, stopPreview }; + const above = points.map((point) => Cesium.Cartesian3.fromDegrees(point.longitude, point.latitude, 300)); + const ground = points.map((point) => Cesium.Cartesian3.fromDegrees(point.longitude, point.latitude, 0)); + const clampFn = viewer.scene?.clampToHeightMostDetailed; + if (typeof clampFn !== 'function') { + return ground.map(applyOffset).filter(Boolean); + } + + try { + const clamped = await clampFn.call(viewer.scene, above); + return ground + .map((fallback: any, index: number) => applyOffset(clamped?.[index] || fallback)) + .filter(Boolean); + } catch { + return ground.map(applyOffset).filter(Boolean); + } + }, [viewerRef, getCesium]); + + const startPreview = useCallback(async (waypoints: BoatWaypointDTO[], speed: number = 2, routeId?: string) => { + const viewer = viewerRef?.current; + const Cesium = getCesium(); + if (!viewer || !Cesium || viewer.isDestroyed?.()) return; + + if (!waypoints || waypoints.length < 2) { + messageApi?.warning('至少需要 2 个航点才能预览'); + return; + } + + if (isPreviewing) { + stopPreview(); + } + + const surfaceGeometry = routeId ? getRouteSurfaceGeometry?.(routeId) : null; + const fallbackWaypointPositions = await buildPreviewWaypointPositions(waypoints); + const routePolylinePositions = Array.isArray(surfaceGeometry?.polyline) && surfaceGeometry.polyline.length >= 2 + ? surfaceGeometry.polyline + : fallbackWaypointPositions; + const waypointPositions = Array.isArray(surfaceGeometry?.waypointPositions) + && surfaceGeometry.waypointPositions.length === waypoints.length + ? surfaceGeometry.waypointPositions + : fallbackWaypointPositions; + if (routePolylinePositions.length < 2 || waypointPositions.length < 2) { + messageApi?.warning('模型仍在加载中,请稍后再试预览'); + return; + } + + const distances: number[] = [0]; + for (let index = 1; index < routePolylinePositions.length; index += 1) { + distances[index] = distances[index - 1] + Cesium.Cartesian3.distance( + routePolylinePositions[index - 1], + routePolylinePositions[index], + ); + } + const totalDistance = distances[distances.length - 1] || 0; + if (totalDistance <= 1) { + setStaticRouteEntitiesVisible(true); + setIsPreviewing(false); + messageApi?.warning('航线过短,无法预览'); + return; + } + + savedCameraStateRef.current = { + position: viewer.camera.position.clone(), + heading: viewer.camera.heading, + pitch: viewer.camera.pitch, + roll: viewer.camera.roll, + }; + + setIsPreviewing(true); + setStaticRouteEntitiesVisible(false); + messageApi?.info('开始航线预览,按 ESC 可退出'); + + const routeMaterial = new Cesium.PolylineGlowMaterialProperty({ + glowPower: 0.35, + color: Cesium.Color.fromCssColorString('#22d3ee').withAlpha(0.95), + }); + + const routeEntity = viewer.entities.add({ + polyline: { + positions: routePolylinePositions, + width: 6, + material: routeMaterial, + depthFailMaterial: routeMaterial, + clampToGround: false, + }, + }); + + const waypointEntities = waypointPositions.map((position, index) => viewer.entities.add({ + position, + point: { + pixelSize: 12, + color: Cesium.Color.fromCssColorString('#ff4d73').withAlpha(0.95), + outlineColor: Cesium.Color.WHITE.withAlpha(0.92), + outlineWidth: 2, + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, + label: { + text: waypoints[index]?.pointName || `航点${index + 1}`, + font: '14px bold sans-serif', + fillColor: Cesium.Color.WHITE, + style: Cesium.LabelStyle.FILL_AND_OUTLINE, + outlineWidth: 3, + outlineColor: Cesium.Color.BLACK, + verticalOrigin: Cesium.VerticalOrigin.BOTTOM, + pixelOffset: new Cesium.Cartesian2(0, -16), + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, + })); + + previewEntitiesRef.current = [routeEntity, ...waypointEntities]; + + const firstPosition = routePolylinePositions[0]; + const initialHeadingRad = getHeadingByDistance( + Cesium, + routePolylinePositions, + distances, + calculateHeading, + 0, + speed, + ); + const liftedFirstPosition = offsetUp(Cesium, firstPosition, BOAT_HEIGHT_OFFSET); + previewBoatEntityRef.current = viewer.entities.add({ + position: liftedFirstPosition, + orientation: Cesium.Transforms?.headingPitchRollQuaternion + ? Cesium.Transforms.headingPitchRollQuaternion( + liftedFirstPosition, + new Cesium.HeadingPitchRoll(initialHeadingRad + MODEL_HEADING_OFFSET, 0, 0), + ) + : undefined, + model: { + uri: `${process.env.CESIUM_BASE_URL || '/'}chuan-model.glb`, + scale: 0.001, + minimumPixelSize: 72, + maximumScale: 220, + runAnimations: true, + }, + }); + + const updateBoatState = (position: any, headingRad: number) => { + if (!previewBoatEntityRef.current) return; + + const liftedPosition = offsetUp(Cesium, position, BOAT_HEIGHT_OFFSET); + previewBoatEntityRef.current.position = liftedPosition; + + if (Cesium.Transforms?.headingPitchRollQuaternion) { + previewBoatEntityRef.current.orientation = Cesium.Transforms.headingPitchRollQuaternion( + liftedPosition, + new Cesium.HeadingPitchRoll(headingRad + MODEL_HEADING_OFFSET, 0, 0), + ); + } + + try { + viewer.camera.lookAt( + offsetUp(Cesium, position, 0.9), + new Cesium.HeadingPitchRange(headingRad, Cesium.Math.toRadians(-20), 22), + ); + } catch { + // ignore + } + }; + + const cornerInfos = buildCornerInfos(Cesium, routePolylinePositions, distances, calculateHeading); + + let lastTime = 0; + let traveled = 0; + let mode: 'move' | 'turn' = 'move'; + let cornerPointer = 0; + let turnStartTime = 0; + let turnDistance = 0; + let turnFromHeadingDeg = 0; + let turnToHeadingDeg = 0; + + const animate = (time: number) => { + const currentViewer = viewerRef?.current; + if (!currentViewer || currentViewer.isDestroyed?.()) { + stopPreview(); + return; + } + + if (!lastTime) lastTime = time; + const deltaSeconds = Math.max(0, (time - lastTime) / 1000); + lastTime = time; + + if (mode === 'move') { + traveled = Math.min(totalDistance, traveled + deltaSeconds * speed); + if (cornerPointer < cornerInfos.length) { + const nextCorner = cornerInfos[cornerPointer]; + if (traveled >= nextCorner.distance) { + traveled = nextCorner.distance; + mode = 'turn'; + cornerPointer += 1; + turnStartTime = time; + turnDistance = nextCorner.distance; + turnFromHeadingDeg = nextCorner.fromHeading; + turnToHeadingDeg = nextCorner.toHeading; + } + } + } else { + traveled = turnDistance; + if (time - turnStartTime >= TURN_HOLD_MS + TURN_ROTATE_MS) { + mode = 'move'; + } + } + + if (traveled >= totalDistance) { + updateBoatState( + routePolylinePositions[routePolylinePositions.length - 1], + Cesium.Math.toRadians(turnToHeadingDeg || 0), + ); + requestRender(); + stopPreview(); + messageApi?.success('航线预览完成'); + return; + } + + const currentPosition = samplePositionAtDistance(Cesium, routePolylinePositions, distances, traveled); + let headingDeg = getHeadingByDistance( + Cesium, + routePolylinePositions, + distances, + calculateHeading, + traveled, + speed, + ); + + if (mode === 'turn') { + const elapsedTurnMs = time - turnStartTime; + if (elapsedTurnMs <= TURN_HOLD_MS) { + headingDeg = turnFromHeadingDeg; + } else { + headingDeg = lerpHeadingDeg( + turnFromHeadingDeg, + turnToHeadingDeg, + (elapsedTurnMs - TURN_HOLD_MS) / Math.max(1, TURN_ROTATE_MS), + ); + } + } else { + turnToHeadingDeg = headingDeg; + } + + updateBoatState(currentPosition, Cesium.Math.toRadians(headingDeg)); + requestRender(); + previewAnimationRef.current = requestAnimationFrame(animate); + }; + + const handleEsc = (event: KeyboardEvent) => { + if (event.key === 'Escape') { + stopPreview(); + } + }; + escHandlerRef.current = handleEsc; + window.addEventListener('keydown', handleEsc); + + requestRender(); + previewAnimationRef.current = requestAnimationFrame(animate); + }, [ + viewerRef, + getCesium, + isPreviewing, + stopPreview, + buildPreviewWaypointPositions, + getRouteSurfaceGeometry, + calculateHeading, + messageApi, + requestRender, + setStaticRouteEntitiesVisible, + ]); + + useEffect(() => { + return () => { + stopPreview(); + }; + }, [stopPreview]); + + return { + isPreviewing, + startPreview, + stopPreview, + }; +} + +function interpolateOnSegment(Cesium: any, start: any, end: any, fraction: number) { + return Cesium.Cartesian3.lerp( + start, + end, + Math.min(1, Math.max(0, fraction)), + new Cesium.Cartesian3(), + ); +} + +function samplePositionAtDistance(Cesium: any, positions: any[], distances: number[], distance: number) { + const clampedDistance = Math.max(0, Math.min(distances[distances.length - 1] || 0, distance)); + const index = findIndexByDistance(distances, clampedDistance); + const previousDistance = distances[index - 1] || 0; + const nextDistance = distances[index] || previousDistance + 1; + const fraction = Math.min( + 1, + Math.max(0, (clampedDistance - previousDistance) / Math.max(1e-6, nextDistance - previousDistance)), + ); + + return interpolateOnSegment(Cesium, positions[index - 1], positions[index], fraction); +} + +function findIndexByDistance(distances: number[], distance: number) { + let low = 0; + let high = distances.length - 1; + + while (low < high) { + const mid = Math.floor((low + high) / 2); + if (distances[mid] < distance) { + low = mid + 1; + } else { + high = mid; + } + } + + return Math.max(1, low); +} + +function getSegmentHeadingDegrees( + Cesium: any, + positions: any[], + calculateHeading: ( + from: { longitude: number; latitude: number }, + to: { longitude: number; latitude: number }, + ) => number, + segmentIndex: number, +) { + const safeIndex = Math.min(Math.max(segmentIndex, 0), positions.length - 2); + const start = positions[safeIndex]; + const end = positions[safeIndex + 1]; + const startCartographic = Cesium.Cartographic.fromCartesian(start); + const endCartographic = Cesium.Cartographic.fromCartesian(end); + + const heading = calculateHeading( + { + longitude: Cesium.Math.toDegrees(startCartographic.longitude), + latitude: Cesium.Math.toDegrees(startCartographic.latitude), + }, + { + longitude: Cesium.Math.toDegrees(endCartographic.longitude), + latitude: Cesium.Math.toDegrees(endCartographic.latitude), + }, + ); + + return heading; +} + +function getHeadingByDistance( + Cesium: any, + positions: any[], + distances: number[], + calculateHeading: ( + from: { longitude: number; latitude: number }, + to: { longitude: number; latitude: number }, + ) => number, + distance: number, + speed: number, +) { + const delta = Math.max(0.6, Math.min(2.5, speed * 0.35)); + const fromPosition = samplePositionAtDistance(Cesium, positions, distances, distance - delta); + const toPosition = samplePositionAtDistance(Cesium, positions, distances, distance + delta); + const fromCartographic = Cesium.Cartographic.fromCartesian(fromPosition); + const toCartographic = Cesium.Cartographic.fromCartesian(toPosition); + + return calculateHeading( + { + longitude: Cesium.Math.toDegrees(fromCartographic.longitude), + latitude: Cesium.Math.toDegrees(fromCartographic.latitude), + }, + { + longitude: Cesium.Math.toDegrees(toCartographic.longitude), + latitude: Cesium.Math.toDegrees(toCartographic.latitude), + }, + ); +} + +function buildCornerInfos( + Cesium: any, + positions: any[], + distances: number[], + calculateHeading: ( + from: { longitude: number; latitude: number }, + to: { longitude: number; latitude: number }, + ) => number, +) { + const cornerInfos: Array<{ distance: number; fromHeading: number; toHeading: number }> = []; + + for (let index = 1; index < positions.length - 1; index += 1) { + const fromHeading = getSegmentHeadingDegrees(Cesium, positions, calculateHeading, index - 1); + const toHeading = getSegmentHeadingDegrees(Cesium, positions, calculateHeading, index); + const angle = Math.abs(shortestDeltaDeg(fromHeading, toHeading)); + + if (angle >= TURN_ANGLE_THRESHOLD_DEG) { + cornerInfos.push({ + distance: distances[index], + fromHeading, + toHeading, + }); + } + } + + return cornerInfos; +} + +function normalizeAngleDeg(degree: number) { + return ((degree % 360) + 360) % 360; +} + +function shortestDeltaDeg(fromDegree: number, toDegree: number) { + let delta = normalizeAngleDeg(toDegree) - normalizeAngleDeg(fromDegree); + if (delta > 180) delta -= 360; + if (delta < -180) delta += 360; + return delta; +} + +function lerpHeadingDeg(fromDegree: number, toDegree: number, fraction: number) { + return normalizeAngleDeg( + fromDegree + shortestDeltaDeg(fromDegree, toDegree) * Math.min(1, Math.max(0, fraction)), + ); +} + +function offsetUp(Cesium: any, origin: any, upMeters: number) { + try { + const enu = Cesium.Transforms.eastNorthUpToFixedFrame(origin); + return Cesium.Matrix4.multiplyByPoint(enu, new Cesium.Cartesian3(0, 0, upMeters), new Cesium.Cartesian3()); + } catch { + return origin; + } } diff --git a/zlt-web/yingyan/src/pages/client/index.less b/zlt-web/yingyan/src/pages/client/index.less index 09cba2d9..2384a707 100644 --- a/zlt-web/yingyan/src/pages/client/index.less +++ b/zlt-web/yingyan/src/pages/client/index.less @@ -189,6 +189,17 @@ flex: 1; height: 100%; position: relative; + min-width: 0; +} + +.execRightPanel { + width: 340px; + height: 100%; + flex-shrink: 0; + + @media (max-width: 1366px) { + width: 300px; + } } /* ========== 沉浸模式标记 ========== */ diff --git a/zlt-web/yingyan/src/pages/client/index.tsx b/zlt-web/yingyan/src/pages/client/index.tsx index 82dfa98c..ad8410c0 100644 --- a/zlt-web/yingyan/src/pages/client/index.tsx +++ b/zlt-web/yingyan/src/pages/client/index.tsx @@ -19,6 +19,7 @@ import LeftPanel from './components/LeftPanel'; import CenterView from './components/CenterView'; import ExecLeftPanel from './components/ExecLeftPanel'; import ExecBottomStrip from './components/ExecBottomStrip'; +import ExecRightPanel from './components/ExecRightPanel'; import { useClientAuth } from './hooks/useClientAuth'; import { useClientSSE } from './hooks/useClientSSE'; import { useRouteData } from './hooks/useRouteData'; @@ -26,7 +27,6 @@ import { useNavigationState } from './hooks/useNavigationState'; import { useNavigationData } from './hooks/useNavigationData'; import styles from './index.less'; -/** 船 Logo SVG */ const ShipLogoIcon: React.FC = () => ( @@ -36,7 +36,6 @@ const ShipLogoIcon: React.FC = () => ( ); -/** 格式化秒数为 HH:MM:SS */ const formatElapsed = (totalSec: number) => { const h = Math.floor(totalSec / 3600).toString().padStart(2, '0'); const m = Math.floor((totalSec % 3600) / 60).toString().padStart(2, '0'); @@ -44,20 +43,54 @@ const formatElapsed = (totalSec: number) => { return `${h}:${m}:${s}`; }; +const calculateDistanceMeters = ( + from: { longitude: number; latitude: number }, + to: { longitude: number; latitude: number }, +) => { + const earthRadius = 6371000; + const dLat = (to.latitude - from.latitude) * Math.PI / 180; + const dLon = (to.longitude - from.longitude) * Math.PI / 180; + const lat1 = from.latitude * Math.PI / 180; + const lat2 = to.latitude * Math.PI / 180; + const a = Math.sin(dLat / 2) ** 2 + + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) ** 2; + return earthRadius * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); +}; + const ClientPage: React.FC = () => { const [messageApi, messageContextHolder] = message.useMessage(); const [modalApi, modalContextHolder] = Modal.useModal(); - // ── 认证 ── - const { boatData: sseBoatData, sseConnected, loading: sseLoading, deviceOffline, connectSSE, disconnectSSE } = useClientSSE(); + + const { + boatData: sseBoatData, + sseConnected, + loading: sseLoading, + deviceOffline, + connectSSE, + disconnectSSE, + } = useClientSSE(); const { deviceSn, deviceInfo, handleLogout } = useClientAuth(disconnectSSE); - // ── 航线数据 ── - const { routes, routeWaypointsMap, selectedRouteId, setSelectedRouteId, routeLoading } = - useRouteData(deviceSn); + const { + routes, + routeWaypointsMap, + selectedRouteId, + setSelectedRouteId, + routeLoading, + } = useRouteData(deviceSn); const boatData = sseBoatData; + const hasBoatPosition = Number.isFinite(boatData?.longitude) && Number.isFinite(boatData?.latitude); + const videoStreamUrl = useMemo(() => { + const rawInfo = deviceInfo as any; + return rawInfo?.videoStreamUrl + || rawInfo?.whepUrl + || rawInfo?.streamUrl + || rawInfo?.videoUrl + || rawInfo?.liveStreamUrl + || undefined; + }, [deviceInfo]); - // ── 沉浸模式状态机 ── const { isPaused, currentWaypointIndex, @@ -72,43 +105,85 @@ const ClientPage: React.FC = () => { handleResumeSailing, handleStopSailing, handleStopPreview, - handleEmergencyStop, handlePreviewChange, } = useNavigationState(deviceSn, selectedRouteId, setSelectedRouteId, routes, messageApi, modalApi); - // ── SSE 连接 ── useEffect(() => { if (!deviceSn) return; connectSSE(deviceSn); - return () => { disconnectSSE(); }; - }, [deviceSn]); + return () => { + disconnectSSE(); + }; + }, [deviceSn, connectSSE, disconnectSSE]); - // ── 沉浸模式计时器 ── const [elapsed, setElapsed] = useState(0); const timerRef = useRef | null>(null); const [previewStartSignal, setPreviewStartSignal] = useState(0); useEffect(() => { if (isImmersive && !isPaused) { - timerRef.current = setInterval(() => setElapsed((s) => s + 1), 1000); + timerRef.current = setInterval(() => setElapsed((seconds) => seconds + 1), 1000); } else if (timerRef.current) { clearInterval(timerRef.current); timerRef.current = null; } - if (!isImmersive) setElapsed(0); - return () => { if (timerRef.current) clearInterval(timerRef.current); }; + + if (!isImmersive) { + setElapsed(0); + } + + return () => { + if (timerRef.current) clearInterval(timerRef.current); + }; }, [isImmersive, isPaused]); - // ── 预览航线回调 ── const handlePreviewRoute = useCallback((routeId: string) => { if (routeId !== selectedRouteId) { setSelectedRouteId(routeId); } - // 延迟递增信号,让 selectedRouteId 先生效触发航点加载 - setTimeout(() => setPreviewStartSignal((s) => s + 1), 200); + setTimeout(() => setPreviewStartSignal((signal) => signal + 1), 200); }, [selectedRouteId, setSelectedRouteId]); - // ── 预先计算航线基础信息(不依赖 boatData) ── + const handleExecuteRoute = useCallback(async (routeId: string) => { + const firstWaypoint = routeWaypointsMap[routeId]?.[0]; + if (!firstWaypoint) { + messageApi.warning('当前航线缺少起始航点,无法执行'); + return; + } + if (!hasBoatPosition) { + messageApi.warning('尚未收到无人船实时位置,暂时不能执行航线'); + return; + } + + const distance = calculateDistanceMeters( + { longitude: boatData!.longitude, latitude: boatData!.latitude }, + { longitude: firstWaypoint.longitude, latitude: firstWaypoint.latitude }, + ); + + if (distance > 200) { + modalApi.warning({ + title: '无法执行航线', + centered: true, + width: 500, + okText: '知道了', + content: ( +
+
+ 无人船距离航线起点约 + + {Math.round(distance)} 米 + +
+
已超过 200 米,请先将无人船驶近起点后再执行。
+
+ ), + }); + return; + } + + await handleStartSailing(routeId); + }, [routeWaypointsMap, boatData, hasBoatPosition, handleStartSailing, messageApi, modalApi]); + const activeWaypointsRaw = useMemo(() => { if (!activeRouteId) return []; return routeWaypointsMap[activeRouteId] || []; @@ -116,45 +191,40 @@ const ClientPage: React.FC = () => { const activeRouteInfoRaw = useMemo(() => { if (!activeRouteId) return null; - return routes.find((r) => r.routeId === activeRouteId) || null; + return routes.find((route) => route.routeId === activeRouteId) || null; }, [activeRouteId, routes]); - // ── 预览模式假数据 ── const effectiveBoatData = useMemo(() => { if (!isPreviewing) return boatData; - // 如果有真实 SSE 数据,优先使用 - if (boatData?.longitude) return boatData; - // 预览模式下根据航线航点和经过时间生成模拟遥测数据 + if (hasBoatPosition) return boatData; if (activeWaypointsRaw.length === 0) return null; - const previewSpeed = 2; // m/s,与预览动画速度一致 + const previewSpeed = 2; const totalDist = activeRouteInfoRaw?.totalDistance || 1000; const traveled = elapsed * previewSpeed; const fraction = Math.min(traveled / totalDist, 0.99); - const wpIdx = Math.min( + const waypointIdx = Math.min( Math.floor(fraction * (activeWaypointsRaw.length - 1)), activeWaypointsRaw.length - 2, ); - const wp = activeWaypointsRaw[wpIdx]; - const nextWp = activeWaypointsRaw[wpIdx + 1] || wp; + const waypoint = activeWaypointsRaw[waypointIdx]; + const nextWaypoint = activeWaypointsRaw[waypointIdx + 1] || waypoint; - // 航段内插值 - const segFrac = (fraction * (activeWaypointsRaw.length - 1)) - wpIdx; - const lon = wp.longitude + (nextWp.longitude - wp.longitude) * segFrac; - const lat = wp.latitude + (nextWp.latitude - wp.latitude) * segFrac; + const segFraction = (fraction * (activeWaypointsRaw.length - 1)) - waypointIdx; + const longitude = waypoint.longitude + (nextWaypoint.longitude - waypoint.longitude) * segFraction; + const latitude = waypoint.latitude + (nextWaypoint.latitude - waypoint.latitude) * segFraction; - // 计算航向 - const dLon = (nextWp.longitude - wp.longitude) * Math.PI / 180; - const lat1 = wp.latitude * Math.PI / 180; - const lat2 = nextWp.latitude * Math.PI / 180; + const dLon = (nextWaypoint.longitude - waypoint.longitude) * Math.PI / 180; + const lat1 = waypoint.latitude * Math.PI / 180; + const lat2 = nextWaypoint.latitude * Math.PI / 180; const y = Math.sin(dLon) * Math.cos(lat2); const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon); const heading = ((Math.atan2(y, x) * 180 / Math.PI) + 360) % 360; return { deviceSn: deviceSn || '', - longitude: lon, - latitude: lat, + longitude, + latitude, heading, speed: previewSpeed, battery: 85, @@ -162,9 +232,8 @@ const ClientPage: React.FC = () => { status: 'preview', recordTime: new Date().toISOString(), } as import('@/types/boatRoute').BoatTelemetryData; - }, [isPreviewing, boatData, activeWaypointsRaw, activeRouteInfoRaw, elapsed, deviceSn]); + }, [isPreviewing, boatData, hasBoatPosition, activeWaypointsRaw, activeRouteInfoRaw, elapsed, deviceSn]); - // ── 导航计算(使用 effectiveBoatData 以便预览模式也有数据) ── const { activeWaypoints, activeRouteInfo, @@ -181,192 +250,194 @@ const ClientPage: React.FC = () => { return ( - {messageContextHolder} - {modalContextHolder} -
- - {/* ========== 普通模式 - 顶部导航栏 ========== */} - {!isImmersive && ( -
-
-
- WAVE PILOT -
- -
- -
-
- - 航线管理 + {messageContextHolder} + {modalContextHolder} +
+ {!isImmersive && ( +
+
+
+ WAVE PILOT
-
- - 实时监控 -
-
- - 历史记录 -
-
-
+
-
- - -
- +
+ + 航线管理 +
+
+ + 实时监控 +
+
+ + 历史记录 +
+
+ +
+ +
+ + +
+ + {deviceInfo.deviceName || deviceSn} +
+
-
-
- )} - - {/* ========== 沉浸模式 - 执行导航栏 ========== */} - {isImmersive && ( -
- - -
-
- {activeRouteInfo?.routeName || '航线'} · {modeLabel} -
-
- {deviceInfo.deviceName || deviceSn} · 已{isPreviewing ? '预览' : '执行'} {formatElapsed(elapsed)}
+ )} -
- - {modeLabel} {modeTag} -
- -
- -
- {isSailing && ( - - )} + {isImmersive && ( +
-
-
- )} - {/* ========== 主体区域 ========== */} -
- - {/* 设备离线遮罩 */} - {deviceOffline && !sseConnected && ( -
-
- -
设备不在线
-
- 无法订阅设备 {deviceInfo.deviceName || deviceSn} 的实时数据 -
- {sseLoading ? '正在重新连接...' : '请检查设备是否已开机并接入网络'} +
+
+ {activeRouteInfo?.routeName || '航线'} · {modeLabel}
- {sseLoading ? ( - - ) : ( -
+ +
+ + {modeLabel} {modeTag} +
+ +
+ +
+ {isSailing && ( + + {isPaused ? : } + {isPaused ? '继续' : '暂停'} + )} +
)} - {/* 左侧边栏 - 普通模式 */} - {!isImmersive && ( -
- -
- )} +
+ {deviceOffline && !sseConnected && ( +
+
+ +
设备不在线
+
+ 无法订阅设备 {deviceInfo.deviceName || deviceSn} 的实时数据 +
+ {sseLoading ? '正在重新连接...' : '请检查设备是否已开机并接入网络'} +
+ {sseLoading ? ( + + ) : ( + + )} +
+
+ )} - {/* 左侧面板 - 沉浸模式 (仪表盘 + 航点列表) */} - {isImmersive && ( - - )} + {!isImmersive && ( +
+ +
+ )} - {/* 地图区域 */} -
- - - {/* 沉浸模式 - 底部航线信息条 */} {isImmersive && ( - )} -
+
+ + + {isSailing && ( + + )} +
+ + {isImmersive && ( +
+ +
+ )} +
-
); diff --git a/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/hooks/useCesiumRouteLibraryRenderer.ts b/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/hooks/useCesiumRouteLibraryRenderer.ts index 84d03703..20ea1132 100644 --- a/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/hooks/useCesiumRouteLibraryRenderer.ts +++ b/zlt-web/yingyan/src/pages/map3d/components/RouteEditor/hooks/useCesiumRouteLibraryRenderer.ts @@ -18,6 +18,11 @@ interface UseCesiumRouteLibraryRendererOptions { routes: RouteLibraryRenderItem[]; } +export interface RouteSurfaceGeometry { + polyline: any[]; + waypointPositions: any[]; +} + export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRendererOptions) { const { viewerRef, routes } = options; @@ -28,7 +33,7 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend const routesRef = useRef(routes); // 贴近模型表面,避免航线“悬浮�? - const ROUTE_RENDER_HEIGHT_OFFSET = 0.05; + const ROUTE_RENDER_HEIGHT_OFFSET = 1.2; const getCesium = useCallback(() => (window as any).Cesium, []); @@ -614,7 +619,18 @@ export function useCesiumRouteLibraryRenderer(options: UseCesiumRouteLibraryRend } }, [viewerRef, getCesium, calculateBounds]); + const getRouteSurfaceGeometry = useCallback((routeId: string): RouteSurfaceGeometry | null => { + const cached = surfaceCacheRef.current.get(routeId); + if (!cached) return null; + + return { + polyline: Array.isArray(cached.polyline) ? cached.polyline.filter(Boolean) : [], + waypointPositions: Array.isArray(cached.waypointPositions) ? cached.waypointPositions.filter(Boolean) : [], + }; + }, []); + return { flyToRoute, + getRouteSurfaceGeometry, }; }