PanoBoxFrame.js 189 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150
  1. import * as THREE from 'three'
  2. import math from './util/math.js'
  3. import common from './util/common.js'
  4. import BoundingMesh from './util/BoundingMesh.js'
  5. import Vectors from './util/Vectors.js'
  6. const version = 'output'
  7. const convertTool = {
  8. getQuaByAim: function (aim, center=new THREE.Vector3, forward=new THREE.Vector3(0, 0, -1)){ //z朝上的坐标系是 forward = new THREE.Vector3(0, 1, 0)
  9. let qua1 = new THREE.Quaternion().setFromUnitVectors(forward, aim.clone().sub(center).normalize())
  10. //或var _ = (new THREE.Matrix4).lookAt(pano.position, aim, new THREE.Vector3(0,1,0)); aimQua = (new THREE.Quaternion).setFromRotationMatrix(_);
  11. return qua1
  12. },
  13. }
  14. //----------------------复制以下内容---------------------------------
  15. let player,
  16. skyBoxTight,
  17. meshGroup,
  18. modelBound = new THREE.Box3(),
  19. ray = new THREE.Raycaster(),
  20. groundPlane = new THREE.Plane(),
  21. groundY,
  22. safeBound,
  23. boundConfirmed, //安全区域应该在扣除每种类型柜子大概的长宽的一半
  24. hue = 0,
  25. startTime,
  26. isLaser,
  27. boxesSolid = []
  28. const MinBoxInitialScore = 0.68 //找不到匹配时,若box分数低于该值,不createSinglePano
  29. let standards = {
  30. cabinet: {
  31. widthNormal: { min: 0.55, max: 1.05 /* max: 0.65 */ }, //widthNormal是不计宽还是厚度的平均宽度 //个别场景如S9yepREK8Jl 宽0.8米
  32. height: { min: 0.3, max: 2.5, standard: 2 },
  33. closeRatio: 0.7, //数值越小越容易findRest。一般在墙上的位置不准要设置大些,扎堆放置的设置小些
  34. },
  35. fire: {
  36. widthNormal: { min: 0.12, max: 0.16 },
  37. height: { min: 0.4, max: 0.58 },
  38. widthSame: true, //长宽相等
  39. closeRatio: 4,
  40. tinyXZ: true, //可以通过它近似确定地面高度
  41. },
  42. air: {
  43. widthNormal: { min: 0.35, max: 0.7 },
  44. width: { min: 0.48, max: 0.75 }, //因为总是斜着放所以范围较大
  45. thick: { min: 0.33, max: 0.5 },
  46. height: { min: 1.2, max: 2.2, standard: 1.8 },
  47. atWall: 0.8,
  48. closeRatio: 1.1,
  49. },
  50. airSmart: {
  51. widthNormal: { min: 0.35, max: 0.7 },
  52. width: { min: 0.48, max: 0.75 }, //因为总是斜着放所以范围较大
  53. thick: { min: 0.33, max: 0.5 },
  54. height: { min: 1.2, max: 2.2, standard: 1.8 },
  55. atWall: 0.8,
  56. closeRatio: 1.1,
  57. },
  58. 'air-hanging': {
  59. widthNormal: { min: 0.3, max: 1 },
  60. width: { min: 0.8, max: 1.1 },
  61. thick: { min: 0.2, max: 0.3 },
  62. height: { min: 0.3, max: 0.5, standard: 0.4 }, //standard是通常出现的最高高度. 有这个值的在离地的时候直接使用该高度
  63. bottom: { min: 0.8, max: 2.0 }, // 不绝对,大部分
  64. atWall: 1, //在墙壁的可能性
  65. closeRatio: 1.5,
  66. },
  67. battery: {
  68. widthNormal: { min: 0.45, max: 1.35 },
  69. width: { min: 0.7, max: 1.4 },
  70. thick: { min: 0.35, max: 0.5 },
  71. height: { min: 0.3, max: 2.5 }, //maxHeight
  72. //有的电池很小。考虑是否追加battery-little 并且限制大电池的长宽高比例
  73. atWall: 0.9,
  74. closeRatio: 0.9,
  75. },
  76. groundBar: {
  77. widthNormal: { min: 0.06, max: 0.4 },
  78. width: { min: 0.3, max: 0.5 },
  79. thick: { min: 0.05, max: 0.08 },
  80. height: { min: 0.1, max: 0.2 },
  81. bottom: { min: 1.2, max: 3 },
  82. atWall: 1,
  83. closeRatio: 2,
  84. },
  85. hlkcWindow: {
  86. widthNormal: { min: 0.08, max: 0.5 },
  87. width: { min: 0.35, max: 0.5 },
  88. thick: { min: 0.03, max: 0.06 },
  89. height: { min: 0.35, max: 0.5 },
  90. bottom: { min: 1.2, max: 3 },
  91. atWall: 1,
  92. closeRatio: 2,
  93. },
  94. electric: {
  95. widthNormal: { min: 0.2, max: 0.7 },
  96. width: { min: 0.5, max: 0.65 },
  97. thick: { min: 0.2, max: 0.3 },
  98. height: { min: 0.5, max: 1 }, //maxHeight 4GqaqNdyjGf一米高
  99. bottom: { min: 0.8, max: 1.8 },
  100. atWall: 1,
  101. closeRatio: 2,
  102. },
  103. monitor: {
  104. widthNormal: { min: 0.08, max: 0.11 },
  105. height: { min: 0.1, max: 0.2, standard: 0.15 }, //maxHeight
  106. bottom: { min: 1.2, max: 3 },
  107. atWall: 1,
  108. closeRatio: 4,
  109. tiny: true, //因为较小且无方向,所以近似一个点,用射线算出的位置比墙面还准,所以其最终位置可用于expandModelBound
  110. },
  111. rowBigBox: {
  112. widthNormal: { min: 0.55, max: Infinity },
  113. height: { min: 0.7, max: 2.4, standard: 2 },
  114. },
  115. /*"cabling-wall":{
  116. },
  117. "cabling-ceil":{
  118. atCeil:1
  119. } */
  120. }
  121. /* const typeNames = {
  122. cabinet : 'cabinet', //标准机柜
  123. air : 'air', //普通空调柜式
  124. battery : 'battery', //蓄电池组
  125. }
  126. */
  127. const typeNames = {
  128. fire: 'extinguisher', //灭火器
  129. monitor: 'surveillance_camera', //监控摄像机 放第一个,用于继续确定边界
  130. hlkcWindow: 'hlkc', //馈线窗
  131. groundBar: 'grounding_bar', //接地排
  132. cabinet: 'equipment_cabinet', //标准机柜
  133. battery: 'accumulator', //蓄电池组
  134. /* ac : 'ac_switchboard', //交流配电柜 //这两种合并,因为差别太小了,见QlJau21WP8G的,在全景图两侧识别的竟然一个ac一个dc
  135. dc : 'dc_distribution', //直流配电设备 */
  136. electric: ['ac_switchboard', 'dc_distribution'],
  137. air: 'sdkt', //普通空调柜式
  138. airSmart: 'ventilation_installation', //智能通风设备
  139. //cabling : 'cabling_rack', //单层走线架 因为在天花板的走线有点复杂,经常断开,无法确定方向所以放弃
  140. }
  141. /* const typeNamesReverse = {} //为了方便访问
  142. for(let i in typeNames){
  143. typeNamesReverse[typeNames[i]] = i
  144. }
  145. */
  146. let addLine = (origin, dir, len, color) => {
  147. return
  148. if (version != 'vision') return
  149. var line1 = LineDraw.createLine([origin, origin.clone().add(dir.clone().multiplyScalar(len || 1))], { color })
  150. //console.log(origin.toArray(), dir.toArray())
  151. meshGroup.add(line1)
  152. return line1
  153. }
  154. let addLabel = (pos, text, { bgcolor, a } = {}) => {
  155. if (version != 'vision') return
  156. let shift = new THREE.Vector3(0, -0.2, 0)
  157. bgcolor = bgcolor ? new THREE.Color(bgcolor) : { r: 1, g: 1, b: 1 }
  158. //let endPos = new THREE.Vector3().addVectors(pos,shift);
  159. text instanceof Array || (text = [text])
  160. let lineCount = Math.round(Math.random() * 6) + 1
  161. let lines = []
  162. while (lineCount-- > 0) {
  163. lines.push('|')
  164. }
  165. text = [...text, ...lines, 'o']
  166. let textMesh = new TextSprite({
  167. text,
  168. textColor: { r: 0, g: 0, b: 0, a: 1 },
  169. backgroundColor: { r: bgcolor.r * 255, g: bgcolor.g * 255, b: bgcolor.b * 250, a: a || 0 },
  170. textBorderColor: { r: bgcolor.r * 255, g: bgcolor.g * 255, b: bgcolor.b * 250, a: a || 0.9 },
  171. textBorderThick: 2,
  172. margin: { x: 0, y: 0 },
  173. borderRadius: 0,
  174. player: player,
  175. sizeInfo: { minSize: 90, maxSize: 300, nearBound: 1, farBound: 7 },
  176. })
  177. textMesh.position.copy(pos)
  178. //textMesh.scale.set(0.3, 0.3, 0.3)
  179. meshGroup.add(textMesh)
  180. textMesh.sprite.position.y += textMesh.sprite.scale.y * 0.4
  181. return textMesh
  182. }
  183. let getBoxFinalPos = info => {
  184. //创建solidbox时的position
  185. let position
  186. let center = getBoxPos(info)
  187. if (standards[info.boxType].bottom) {
  188. //悬挂
  189. position = center
  190. } else {
  191. position = center.clone().setY(groundY + info.size.y / 2) //使着地
  192. }
  193. return position
  194. }
  195. const axises = [
  196. new THREE.Vector3(-1, 1, -1),
  197. new THREE.Vector3(1, 1, -1),
  198. new THREE.Vector3(1, 1, 1),
  199. new THREE.Vector3(-1, 1, 1),
  200. new THREE.Vector3(-1, -1, -1),
  201. new THREE.Vector3(1, -1, -1),
  202. new THREE.Vector3(1, -1, 1),
  203. new THREE.Vector3(-1, -1, 1),
  204. ]
  205. let traverse = (info, fun) => {
  206. //忽略.infos的row 的信息
  207. fun(info)
  208. info.list && info.list.forEach(a => traverse(a, fun))
  209. info.mixedFrom && info.mixedFrom.forEach(a => traverse(a, fun))
  210. }
  211. class Box {
  212. //结果
  213. constructor(info) {
  214. //preDealBox(info)
  215. this.setFromInfo(info)
  216. this.buildFromData || (this.name = this.boxType + '-' + this.name)
  217. if (version == 'vision' && (this.buildFromData || boundConfirmed)) this.draw()
  218. boxesSolid.push(this)
  219. }
  220. setFromInfo(info) {
  221. for (let i in info) {
  222. this[i] = info[i]
  223. }
  224. /* let h = info.size.y
  225. let standardH = standards[info.boxType].height.standard
  226. if (h > standardH) {
  227. h = standardH + Math.log(1 + (h - standardH) / 2) //Math.log2: 以2为底的对数 ,Math.log:自然对数
  228. info.size.y = h
  229. } */
  230. this.position = this.buildFromData ? this.center : getBoxFinalPos(this)
  231. let bound = new THREE.Box3().setFromCenterAndSize(this.position, this.size)
  232. this.bound = bound
  233. }
  234. draw() {
  235. hue += 0.23
  236. var color = new THREE.Color().setHSL(hue, 0.9, 0.85)
  237. this.boxHelper = new THREE.Box3Helper(this.bound, color)
  238. this.boxHelper.material.depthTest = false
  239. this.boxHelper.material.transparent = true
  240. this.boxHelper.renderOrder = 30
  241. /* let { warnStr, exStr } = this
  242. warnStr && (exStr += `【${warnStr}】`) */
  243. this.label = addLabel(this.position, /* exStr ? [this.name, exStr] : */ this.score ? [this.name, this.score.toFixed(1)] : this.name, { bgcolor: color })
  244. /* //color = new THREE.Color('#fff')
  245. let box = new THREE.Mesh(new THREE.BoxBufferGeometry(), new THREE.MeshBasicMaterial({color, opacity:0.5, transparent:true}))
  246. box.position.copy(this.position)
  247. box.scale.copy(this.size)
  248. meshGroup.add(box) */
  249. meshGroup.add(this.boxHelper)
  250. }
  251. dispose() {
  252. let index = boxesSolid.indexOf(this)
  253. if (index > -1) {
  254. boxesSolid.splice(index, 1)
  255. if (version == 'vision' && boundConfirmed) {
  256. this.label.sprite.material.opacity = 0.3
  257. this.boxHelper.material.opacity = 0.2
  258. }
  259. }
  260. }
  261. traversePair(fun) {
  262. traverse(this, fun)
  263. }
  264. getDirection() {
  265. //获得正面朝向。 需要全部box都创建完再调用
  266. let xProp = this.xProp
  267. let dir
  268. //哪边pano多朝哪边
  269. if (this.boxType == 'cabinet' && this.name.includes('row')) {
  270. if (this.infos.box.length > 1) {
  271. let k = this.infos.reduce((w, c) => {
  272. return w + c.k
  273. }, 0)
  274. xProp = k > 1 ? 'width' : 'thick'
  275. } else {
  276. //直接使用别的多box的row的方向 ,大多数都相同(会有例外,无所谓了)
  277. let rows = boxesSolid.filter(e => e.boxType == 'cabinet' && e.name.includes('row') && e.dirQua)
  278. rows.sort((a, b) => b.infos.box.length - a.infos.box.length)
  279. let box = rows[0]
  280. if (box) {
  281. return (this.dirQua = box.dirQua)
  282. }
  283. }
  284. }
  285. if (!xProp) {
  286. //根据房间的长宽 散落的cabinet。 fire monitor
  287. let { xWidthPossible, yWidthPossible } = getBoxDirProp(this, true)
  288. xProp = this.xProp
  289. /* if(Math.abs(xWidthPossible - yWidthPossible) < 0.3){
  290. let size = new THREE.Vector3()
  291. safeBound.getSize(size)
  292. xWidthPossible += (size.x - size.z) * 0.5
  293. if(xWidthPossible > yWidthPossible){
  294. xProp = 'width'
  295. }
  296. } */
  297. }
  298. if (xProp) {
  299. if (!this.panosDir) getPanosDir(this)
  300. if (xProp == 'width') {
  301. if (Math.abs(this.panosDir['z+']) < Math.abs(this.panosDir['z-'])) {
  302. //朝-z//也就是新坐标系的y
  303. //this.dirQua='下'
  304. dir = new THREE.Vector3(0, 1, 0)
  305. } else {
  306. //朝+z
  307. //this.dirQua='上'
  308. dir = new THREE.Vector3(0, -1, 0)
  309. }
  310. } else {
  311. if (Math.abs(this.panosDir['x+']) < Math.abs(this.panosDir['x-'])) {
  312. //朝-x
  313. //this.dirQua='右'
  314. dir = new THREE.Vector3(-1, 0, 0)
  315. } else {
  316. //朝+x
  317. //this.dirQua='左'
  318. dir = new THREE.Vector3(1, 0, 0)
  319. }
  320. }
  321. }
  322. //addLabel(this.position, this.dirQua)
  323. this.dirQua = convertTool.getQuaByAim(dir, new THREE.Vector3(), new THREE.Vector3(0, 1, 0))
  324. return this.dirQua
  325. /*飞到俯视图查看(不旋转视图,x朝右,z朝下)。以下四个qua是四个墙壁每个墙壁上的dirQua。
  326. _x: 0, _y: -0, _z: 1, _w: 0
  327. _x: 0, _y: 0, _z: -0.707, _w: 0.707 _x: 0, _y: -0, _z: 0.707, _w: 0.707
  328. x: 0, _y: 0, _z: 0, _w: 1
  329. */
  330. }
  331. toJson() {
  332. //转出的坐标系是z朝上的
  333. let category = typeNames[this.boxType]
  334. if (category instanceof Array) {
  335. let scoreMap = new Map()
  336. category = category.slice(0)
  337. category.forEach(e => scoreMap.set(e, 0)) //初始化
  338. //判断boxType: 寻找所使用的box总分最高的boxType
  339. let add = box => {
  340. if (!box) return
  341. let score = scoreMap.get(box.category) + box.score
  342. scoreMap.set(box.category, score)
  343. }
  344. this.traversePair(e => {
  345. add(e.box0)
  346. add(e.box1)
  347. })
  348. category = category.sort((a, b) => {
  349. return scoreMap.get(b) - scoreMap.get(a)
  350. })
  351. category = category[0] //最高分
  352. }
  353. this.getDirection()
  354. let json = {
  355. points: axises.map(axis => math.invertVisionVector(new THREE.Vector3().addVectors(this.position, this.size.clone().multiply(axis).multiplyScalar(0.5))).toArray()),
  356. category,
  357. type: this.boxType,
  358. sid: this.name,
  359. quaternion: this.dirQua.toArray(),
  360. }
  361. return json
  362. }
  363. }
  364. // 2d坐标转3d坐标
  365. let getDirByUV = (uv, pano) => {
  366. // 计算方向向量
  367. let yaw = -uv.x * (Math.PI * 2)
  368. let pitch = Math.PI / 2 - uv.y * Math.PI
  369. let dir = new THREE.Vector3()
  370. dir.copy(Vectors.RIGHT).applyAxisAngle(Vectors.BACK, pitch).applyAxisAngle(Vectors.UP, yaw).applyQuaternion(pano.quaternion)
  371. return dir
  372. }
  373. let getCenterDir = box => {
  374. if (box.centerDir) return
  375. //假设不存在在box中间拍摄的情况,所以y不会横跨两边
  376. let bbox = box.bbox2
  377. let center = { x: getBbox2center(bbox[0], bbox[2]), y: (bbox[1] + bbox[3]) / 2 }
  378. box.bbox2CenterX = center.x
  379. let dir = getDirByUV(center, box.pano)
  380. box.centerDir = dir
  381. let centerTop = { x: center.x, y: bbox[1] }
  382. box.centerTopDir = getDirByUV(centerTop, box.pano)
  383. let centerBtm = { x: center.x, y: bbox[3] }
  384. box.centerBtmDir = getDirByUV(centerBtm, box.pano)
  385. let leftBtm = { x: bbox[0], y: bbox[3] }
  386. box.leftBtmDir = getDirByUV(leftBtm, box.pano)
  387. let rightBtm = { x: bbox[2], y: bbox[3] }
  388. box.rightBtmDir = getDirByUV(rightBtm, box.pano)
  389. }
  390. let getOtherPos = box => {
  391. if (!box.boxType) return
  392. let config = standards[box.boxType]
  393. if (!boundConfirmed) {
  394. if (!config.bottom) {
  395. ray.set(box.pano.position, box.centerBtmDir)
  396. box.btmPosPredict = ray.ray.intersectPlane(groundPlane, new THREE.Vector3()) //没有的话就在空中 (部分air-hanging也会有)。 fire的这个值会较大误差,因为groundY还不确定,但不影响,因只用它射线交点的位置。
  397. if (box.btmPosPredict) {
  398. let dir2d = new THREE.Vector2(box.centerBtmDir.x, box.centerBtmDir.z).normalize()
  399. let { min, max } = standards[box.boxType].widthNormal
  400. min = min * 0.4
  401. max = max * 0.4
  402. let minA = Math.min(Math.abs(dir2d.x), Math.abs(dir2d.y))
  403. const depth = math.linearClamp(minA, 0, 1, min, max)
  404. /* const depth = box.category == typeNames.cabinet ? 0.5 : 0.4
  405. */
  406. dir2d = dir2d.clone().multiplyScalar(depth)
  407. box.btmPosPredict.x += dir2d.x
  408. box.btmPosPredict.z += dir2d.y
  409. //addLabel(box.btmPosPredict,'b_'+box.category+"_"+box.sid, {bgcolor:'#6ff',a:0.1})
  410. //box.btmPosPredict.clamp(safeBound.min, safeBound.max)
  411. }
  412. }
  413. return
  414. }
  415. if (!box.posAtWall && config.atWall > 0) {
  416. //console.log(box.sid, 'getPosWall')
  417. const shrink = config.thick ? config.thick.min : config.widthNormal.min
  418. ray.set(box.pano.position, box.centerDir)
  419. let o = ray.intersectObjects([skyBoxTight])
  420. if (o[0]) box.posAtWall = new THREE.Vector3().addVectors(box.pano.position, box.centerDir.clone().multiplyScalar(o[0].distance - shrink))
  421. //因墙壁不准确,所以还是尽量不用墙的位置
  422. /* if(box.btmPos){
  423. let wallRatio = 0.5;
  424. if(new THREE.Vector3().subVectors(box.btmPos, box.posAtWall).setY(0).length() > 1 )wallRatio = 0.2 //可能墙壁位置不准,靠后了
  425. box.predictCenter = new THREE.Vector3().addVectors(box.btmPos.clone().multiplyScalar(1-wallRatio), box.posAtWall.clone().multiplyScalar(wallRatio))
  426. //box.predictCenter = new THREE.Vector3().addVectors(box.posAtWall, box.btmPos).multiplyScalar(0.5) //也许能当中心点? 虽然y会低一些
  427. addLabel(box.predictCenter, box.sid+'-preC')
  428. } */
  429. }
  430. if (!box.btmPos) {
  431. getBoxBtm(box)
  432. }
  433. if (!box.topPos) {
  434. getBoxTop(box)
  435. }
  436. }
  437. let getUVs = (box, imageWidth, imageHeight) => {
  438. if (box.bbox2) return
  439. let uvs = []
  440. if (!imageWidth) {
  441. imageWidth = boxFrame.datas[box.pano.id].imageWidth
  442. imageHeight = boxFrame.datas[box.pano.id].imageHeight
  443. }
  444. if (imageWidth != imageWidth || imageHeight != imageHeight) {
  445. console.log(imageWidth, imageHeight)
  446. }
  447. box.bbox2 = box.bbox.map((e, i) => {
  448. //(x1,y1,x2,y2)
  449. return i % 2 == 0 ? e / imageWidth /* + 0.25 */ : e / imageHeight
  450. })
  451. }
  452. let getBoxBase = (box, imageWidth, imageHeight) => {
  453. getBoxType(box)
  454. getUVs(box, imageWidth, imageHeight)
  455. getCenterDir(box)
  456. getOtherPos(box)
  457. }
  458. let getBbox2Diff = (x1, x2) => {
  459. //获取x1-x2,如果x1在x2右边则为正
  460. if (Math.abs(x1 - x2) < 0.5) return x1 - x2
  461. else {
  462. if (x1 > x2) x1 -= 1
  463. else x2 -= 1
  464. return x1 - x2
  465. }
  466. }
  467. let getBbox2center = (x1, x2) => {
  468. //找中间位置
  469. if (Math.abs(x1 - x2) > 0.5) {
  470. //永远找小于180度的那一边
  471. return (x1 + x2 + 1) / 2 //另外半边
  472. } else {
  473. return (x1 + x2) / 2
  474. }
  475. }
  476. let getBoxTop = info => {
  477. /* if(info.sid == 'pano0-11(mix4,8)'){
  478. console.log(5)
  479. } */
  480. if (info.box1) {
  481. let o2 = getIntersect2(info.box0.pano.position, info.box0.centerTopDir, info.box1.pano.position, info.box1.centerTopDir)
  482. info.topPos = o2.pos3d
  483. info.diffHeight = o2.mid2 ? o2.mid2.distanceTo(o2.mid1) : 1
  484. if (info.box0.topPos && info.box1.topPos) {
  485. info.topPos.y = (info.box0.topPos.y + info.box1.topPos.y) / 2 //原先的不准
  486. }
  487. } else {
  488. //取btm上方对应的位置 ( 因为和skybox的交点会因离墙远而偏上或偏下)
  489. let box = info.box0 || info
  490. let btm = box.btmPos
  491. if (!btm) {
  492. btm = getBoxBtm(info)
  493. }
  494. box.topPos = btm.clone() //xz同btm,要求y
  495. let xDelta = btm.x - box.pano.position.x
  496. let zDelta = btm.z - box.pano.position.z
  497. let yDelta
  498. //因为pano有旋转所以btm和top的xz其实是不一样的,所以会有误差。 故这里选择delta较大的
  499. if (Math.abs(xDelta) < Math.abs(zDelta)) {
  500. yDelta = (zDelta * box.centerTopDir.y) / box.centerTopDir.z
  501. /* console.log('use z', box)
  502. if(Math.abs(xDelta)<0.1)console.error('!!!!!!!!!!!!!!!!!!!!!!! xDelta',xDelta, box.sid ) */
  503. } else {
  504. yDelta = (xDelta * box.centerTopDir.y) / box.centerTopDir.x
  505. // console.log('use x', box)
  506. }
  507. box.topPos.y = yDelta + box.pano.position.y
  508. let minHeight = /* info.boxType ? standards[info.boxType].height.min : box.category == typeNames.air ? 0.5 : */ standards[getBoxType(box)].height.min
  509. let diffH = Math.max(box.topPos.y - btm.y, minHeight)
  510. box.topPos.y = btm.y + diffH
  511. info.topPos = box.topPos
  512. /* if (box.sid == 'pano2-1') {
  513. addLabel(box.topPos,'t_'+box.sid,{bgcolor:'#ff4399'})
  514. addLine(box.pano.position,box.centerTopDir, 20)
  515. } */
  516. }
  517. return info.topPos
  518. }
  519. let getBoxBtm = info => {
  520. if (info.box1) {
  521. let o2 = getIntersect2(info.box0.pano.position, info.box0.centerBtmDir, info.box1.pano.position, info.box1.centerBtmDir)
  522. info.btmPos = o2.pos3d
  523. //info.btmPos.y = (info.box0.btmPos.y + info.box1.btmPos.y)/2 //原先的不准
  524. } else {
  525. let box = info.box0 || info
  526. if (!box.btmPos) {
  527. if (box.sid == 'pano0-7') {
  528. console.log(3)
  529. addLine(box.pano.position, box.centerBtmDir, 20)
  530. }
  531. if (!boundConfirmed) {
  532. return box.btmPosPredict
  533. }
  534. ray.set(box.pano.position, box.centerBtmDir)
  535. let o = ray.intersectObjects([skyBoxTight]) //如果skybound有问题,位置就会错
  536. box.btmPosOri = o[0].point.clone()
  537. let depth //缩进 //let depth = Math.abs(o[0].face.normal.y) > 0.9 ? 0.4 : -0.4
  538. getBoxType(box)
  539. let dir2d = new THREE.Vector2(box.centerBtmDir.x, box.centerBtmDir.z).normalize()
  540. if (standards[box.boxType].thick && standards[box.boxType].atWall /* box.boxType == 'battery' */) {
  541. //平贴于墙上,且厚度和宽度相差较大
  542. //注:air-hanging主要用的是posAtWall
  543. let { min, max } = standards[box.boxType].widthNormal
  544. min = min * 0.3
  545. max = max * 0.5
  546. if (!box.xProp) getBoxDirProp(box)
  547. if (box.xProp == 'width') {
  548. depth = math.linearClamp(Math.abs(dir2d.x), 0, 1, min, max)
  549. } else {
  550. depth = math.linearClamp(Math.abs(dir2d.y), 0, 1, min, max)
  551. }
  552. } else {
  553. let w = standards[box.boxType].thick || standards[box.boxType].widthNormal
  554. let w0 = (w.min + w.max) / 2
  555. let min = w0 * 0.5,
  556. max = w0 * 0.8
  557. let minA = Math.min(Math.abs(box.centerBtmDir.x), Math.abs(box.centerBtmDir.z))
  558. depth = math.linearClamp(minA, 0, 0.707, min /* 0.3 */, max /* 0.5 */) //在45度时需要最长的距离。主要针对cabinet
  559. }
  560. if (Math.abs(o[0].face.normal.y) < 0.9) {
  561. if (standards[box.boxType].atWall || o[0].point.y - groundY > 0.3) {
  562. //battery的识别框比较乱,有可能一个电池被识别出好几个,所以
  563. depth *= -1 //at wall
  564. }
  565. }
  566. let dir2d1 = dir2d.clone().multiplyScalar(depth)
  567. box.btmPos = o[0].point.clone()
  568. box.btmPos.x += dir2d1.x
  569. box.btmPos.z += dir2d1.y
  570. //addLabel(box.btmPos,'b_'+box.sid,{bgcolor:'#ff4399'})
  571. }
  572. info.btmPos = box.btmPos
  573. }
  574. return info.btmPos
  575. }
  576. let getIntersect = (pano0Pos, dir0, pano1Pos, dir1) => {
  577. let pos0 = new THREE.Vector3().addVectors(pano0Pos, dir0)
  578. let pos1 = new THREE.Vector3().addVectors(pano1Pos, dir1)
  579. /* var {pos3d, mid1, mid2, behind} = math.getLineIntersect({ A: pano0Pos.clone(), B: pano1Pos.clone(), p1: pos0, p2: pos1 })
  580. */ //三维线若接近平行,算出的交点可能很近,不是实际应该无交点才对
  581. var pos2d = math.isLineIntersect(
  582. [
  583. { x: pano0Pos.x, y: pano0Pos.z },
  584. { x: pos0.x, y: pos0.z },
  585. ],
  586. [
  587. { x: pano1Pos.x, y: pano1Pos.z },
  588. { x: pos1.x, y: pos1.z },
  589. ],
  590. true
  591. ) //优先考虑水平面方向的交点
  592. if (pos2d) {
  593. let y0 = ((pos2d.x - pano0Pos.x) * dir0.y) / dir0.x + pano0Pos.y
  594. let y1 = ((pos2d.x - pano1Pos.x) * dir1.y) / dir1.x + pano1Pos.y
  595. //console.log(y1-y0)
  596. let pos3d = new THREE.Vector3(pos2d.x, (y0 + y1) / 2, pos2d.y)
  597. return { pos3d, diffHeight: Math.abs(y0 - y1) } //diffHeight越小越好
  598. }
  599. }
  600. //究竟哪个比较准 - - 可能两个都判断?
  601. let getIntersect2 = (pano0Pos, dir0, pano1Pos, dir1) => {
  602. let pos0 = new THREE.Vector3().addVectors(pano0Pos, dir0)
  603. let pos1 = new THREE.Vector3().addVectors(pano1Pos, dir1)
  604. let o = math.getLineIntersect2({ A: pano0Pos.clone(), B: pano1Pos.clone(), p1: pos0, p2: pos1, dir0, dir1 }) //不用getLineIntersect,因为这个针对热点写的,当无交点时选用的点不是想要的
  605. if (!o.pos3d) {
  606. console.error('getIntersect2 no result? ?')
  607. }
  608. return o
  609. }
  610. let getBoxPos = info => {
  611. let boxType = getBoxType(info)
  612. return (
  613. (info.preDealRes && info.preDealRes.position) ||
  614. info.center ||
  615. (boxType && (standards[boxType].atWall > 0.5 && standards[boxType].bottom ? info.posAtWall : info.btmPos || info.btmPosPredict)) ||
  616. info.posAtWall
  617. )
  618. }
  619. let isType = (category, type) => {
  620. return type == category || typeNames[type] instanceof Array ? typeNames[type].includes(category) : typeNames[type] == category
  621. }
  622. let getBoxType = info => {
  623. if (info.boxType) return info.boxType
  624. let category = info.category || info.box0.category
  625. if (category == 'rowBigBox') info.boxType = 'rowBigBox'
  626. else {
  627. let type
  628. if (category == 'ac_switchboard') {
  629. console.log(1)
  630. }
  631. for (let i in typeNames) {
  632. /* if (i == category || typeNames[i] instanceof Array ? typeNames[i].includes(category) : typeNames[i] == category) {
  633. type = i
  634. break //type = typeNamesReverse[type]
  635. } */
  636. if (isType(category, i)) {
  637. type = i
  638. break
  639. }
  640. }
  641. /* if(type == 'ac' || type == 'dc'){
  642. type = 'electric' //合并
  643. } */
  644. info.boxType = type
  645. }
  646. return info.boxType
  647. }
  648. /* let getBoxType = info => {
  649. let type = info.category || info.box0.category
  650. if (type == 'air') {
  651. let btm = info.btmPos || info.btmPos //btmPosAtWall
  652. if (!btm) {
  653. btm = getBoxBtm(info)
  654. }
  655. if (!btm) return
  656. let center = info.posAtWall || (info.preDealRes && info.preDealRes.position) || info.center
  657. const s = standards['air-hanging']
  658. if (btm.y - groundY > s.bottom.min) {
  659. let h0 = btm.y - groundY
  660. let h1 = (modelBound.max.y - center.y) / (modelBound.max.y - modelBound.min.y)
  661. let h2 = center.y - btm.y
  662. let score = h0 * 2 - h1 * 3 - h2 * 3
  663. if (score > 0) {
  664. type = 'air-hanging'
  665. }
  666. //console.error( score, h0,h1,h2, info.sid||info.name)
  667. } //注意:如果air被遮住底部,露出的部分只有一点,还是有可能被识别成air-hanging。只能希望
  668. //console.error( type, info.sid||info.name)
  669. }
  670. if (info.box0) {
  671. info.boxType = type
  672. //info.box1 && (info.box1.type = type) //因为box0和box1不一定匹配,所以不能直接赋值
  673. } else {
  674. info.type = type
  675. }
  676. } */
  677. let getPanosDir = (info, center) => {
  678. center = center || getBoxPos(info)
  679. let dirs = { 'x+': 0, 'x-': 0, 'z+': 0, 'z-': 0, got: false }
  680. let getDirs = () => {
  681. //靠墙的在它到墙之间是不会有漫游点的
  682. if (dirs.got || !center) return
  683. player.model.panos.list.forEach(pano => {
  684. let dir = new THREE.Vector3().subVectors(pano.position, center)
  685. if (dir.x > 0) {
  686. dirs['x+'] += dir.x
  687. } else {
  688. dirs['x-'] += dir.x
  689. }
  690. if (dir.z > 0) {
  691. dirs['z+'] += dir.z
  692. } else {
  693. dirs['z-'] += dir.z
  694. }
  695. })
  696. dirs.got = true
  697. }
  698. getDirs()
  699. if (info.panosDir) {
  700. console.error('already has dir')
  701. }
  702. info.panosDir = dirs
  703. return dirs
  704. }
  705. let getBoxDirProp = (info, force) => {
  706. //仅适用于方形单个房间房间,不可以是多边形、两个房间
  707. let xProp, yProp
  708. if (info.name == 'pano10-8&pano12-6') {
  709. console.log(4)
  710. }
  711. //if (info.boxType == 'battery' || info.boxType == 'air-hanging' || info.boxType == 'air' || info.category == 'battery' || info.category == 'air') {
  712. if ((standards[info.boxType].atWall && standards[info.boxType].thick) || force) {
  713. //根据比例判断
  714. /* let r1 = Math.abs((center.x - skyBoxTight.position.x) / (center.z - skyBoxTight.position.z))
  715. let r2 = player.model.size.x / player.model.size.z
  716. if(!math.closeTo(r1,r2, 0.05)){
  717. if (r1<r2) {
  718. ;(xProp = 'width'), (yProp = 'thick') //贴附x(横)墙
  719. } else {
  720. ;(xProp = 'thick'), (yProp = 'width') //贴附y(竖)墙
  721. }
  722. matchInfo.xProp = xProp
  723. matchInfo.yProp = yProp
  724. } */
  725. //根据距离判断
  726. let center = getBoxPos(info)
  727. let bound = safeBound
  728. let minXDiff = Math.min(center.x - bound.min.x, bound.max.x - center.x)
  729. let minYDiff = Math.min(center.z - bound.min.z, bound.max.z - center.z)
  730. let dirs = getPanosDir(info, center)
  731. let noX = dirs['x+'] == 0 || dirs['x-'] == 0,
  732. noZ = dirs['z+'] == 0 || dirs['z-'] == 0
  733. //yi6dsPTWwFM klkcWindow pano0-1&pano2-0
  734. if (dirs['x+'] == 0 && dirs['x-'] != 0) {
  735. minXDiff = bound.max.x - center.x
  736. } else if (dirs['x-'] == 0 && dirs['x+'] != 0) {
  737. minXDiff = center.x - bound.min.x
  738. }
  739. if (dirs['z+'] == 0 && dirs['z-'] != 0) {
  740. minYDiff = bound.max.z - center.z
  741. } else if (dirs['z-'] == 0 && dirs['z+'] != 0) {
  742. minYDiff = center.z - bound.min.z
  743. }
  744. let xWidthPossible = noZ ? 1 : 0,
  745. yWidthPossible = noX ? 1 : 0
  746. xWidthPossible += minXDiff - minYDiff
  747. if (!math.closeTo(xWidthPossible, yWidthPossible, 0.2) && (minXDiff < 0.7 || minYDiff < 0.7)) {
  748. if (xWidthPossible < yWidthPossible) {
  749. ;(xProp = 'thick'), (yProp = 'width') //贴附y(竖)墙
  750. } else {
  751. ;(xProp = 'width'), (yProp = 'thick') //贴附x(横)墙
  752. }
  753. }
  754. if (!xProp) {
  755. if (!force) {
  756. //force的话是fire等无方向的类型
  757. if (info.category) {
  758. //是box
  759. info.pose || (info.pose = getBoxPoseByPos(info, center))
  760. xWidthPossible += info.pose.xWidthPossible
  761. yWidthPossible += info.pose.yWidthPossible
  762. } else {
  763. traverse(info, info => {
  764. if (info.boxposes) {
  765. //是matchInfo
  766. info.boxposes.forEach(e => {
  767. xWidthPossible += e.xWidthPossible
  768. yWidthPossible += e.yWidthPossible
  769. })
  770. }
  771. })
  772. }
  773. }
  774. /* if(noX!=noZ){
  775. if(noX)xWidthPossible
  776. } */
  777. if (xWidthPossible > yWidthPossible) {
  778. ;(xProp = 'width'), (yProp = 'thick') //贴附x(横)墙
  779. } else {
  780. ;(xProp = 'thick'), (yProp = 'width') //贴附y(竖)墙
  781. }
  782. }
  783. xProp && ((info.xProp = xProp), (info.yProp = yProp))
  784. return { xWidthPossible, yWidthPossible }
  785. }
  786. }
  787. let preDealBox = matchInfo => {
  788. if (matchInfo.preDealRes || !matchInfo.center) return
  789. matchInfo.preDealRes = {}
  790. matchInfo.boxType || getBoxType(matchInfo)
  791. let config = standards[matchInfo.boxType]
  792. let minWidth = config.widthNormal.min
  793. let needGetPose
  794. let dis = safeBound.distanceToPoint(matchInfo.center)
  795. if (matchInfo.name == 'pano2-5') {
  796. console.log(4)
  797. }
  798. if (dis > 0.3 && !config.tiny && !config.tinyXZ) {
  799. //Tmo1vLp9Q13: hlkcWindow超出才准确
  800. //tiny的位置优先级高于bound,因为他们可以确定bound
  801. /* matchInfo.str && matchInfo.str.includes('outsideBound') */
  802. //const shrink = minWidth * 0.85
  803. //addLabel(matchInfo.center, '原')
  804. let finalPos = matchInfo.center.clone().clamp(safeBound.min, safeBound.max)
  805. matchInfo.preDealRes.position = finalPos
  806. //addLabel(finalPos, 'finalPos')
  807. getBoxType(matchInfo)
  808. needGetPose = true
  809. }
  810. let center = getBoxPos(matchInfo)
  811. if (needGetPose || !matchInfo.boxposes) {
  812. matchInfo.boxposes = []
  813. ;[matchInfo.box0, matchInfo.box1].forEach(box => {
  814. box && matchInfo.boxposes.push(getBoxPoseByPos(box, center))
  815. })
  816. }
  817. //-----------------
  818. getBoxDirProp(matchInfo)
  819. }
  820. let getBoxPoseByPos = (box, centerPos, addDis = 0) => {
  821. //当得知box的大概位置时,求box在这个角度上的宽度、朝向
  822. //在这个方向看的box的宽度
  823. let config = standards[box.boxType]
  824. let angle = getBbox2Diff(box.bbox2[2], box.bbox2[0]) * Math.PI //角度的一半
  825. let dis = new THREE.Vector3().subVectors(box.pano.position, centerPos).setY(0).length() + addDis
  826. let projectWidth = 2 * Math.tan(angle) * dis //投影宽度 (准确的投影宽度无法求得,只能近似)
  827. let camDir = /* new THREE.Vector2(centerPos.x-box.pano.position.x, centerPos.z-box.pano.position.z).normalize() */ box.centerDir.clone().setY(0).normalize()
  828. let camTangent = math.getNormal({
  829. points: [
  830. { x: 0, y: 0 },
  831. /* camDir */ { x: camDir.x, y: camDir.z },
  832. ],
  833. }) //视线切线方向
  834. camTangent.x = Math.abs(camTangent.x)
  835. camTangent.y = Math.abs(camTangent.y)
  836. if (box.sid == 'pano4-6') {
  837. console.log(7)
  838. }
  839. const maxWidth = config.widthNormal.max
  840. const minWidth = config.widthNormal.min
  841. let minProjectWidth //= (camTangent.x + camTangent.y) * minWidth
  842. let maxProjectWidth //= (camTangent.x + camTangent.y) * maxWidth
  843. let maxX, maxY, minX, minY
  844. if (!standards[box.boxType].thick) {
  845. minProjectWidth = (camTangent.x + camTangent.y) * minWidth
  846. maxProjectWidth = (camTangent.x + camTangent.y) * maxWidth //该角度下该类型允许的最大投影距离
  847. maxX = THREE.MathUtils.clamp((projectWidth - minWidth * camTangent.y) / camTangent.x, minWidth, maxWidth) //可得x的最大值(假设y为最小值)
  848. maxY = THREE.MathUtils.clamp((projectWidth - minWidth * camTangent.x) / camTangent.y, minWidth, maxWidth) //可得y的最大值(假设x为最小值)
  849. minX = THREE.MathUtils.clamp((projectWidth - maxWidth * camTangent.y) / camTangent.x, minWidth, maxWidth) //可得x的最小值(假设y为最大值)
  850. minY = THREE.MathUtils.clamp((projectWidth - maxWidth * camTangent.x) / camTangent.y, minWidth, maxWidth) //可得y的最小值(假设x为最大值)
  851. } else {
  852. const minThick_ = config.thick.min
  853. const minWidth_ = config.width.min
  854. const maxThick_ = config.thick.max
  855. const maxWidth_ = config.width.max
  856. let maxProjectWidth1 = camTangent.x * maxWidth_ + camTangent.y * maxThick_
  857. let maxProjectWidth2 = camTangent.x * maxThick_ + camTangent.y * maxWidth_
  858. let minProjectWidth1 = camTangent.x * minWidth_ + camTangent.y * minThick_
  859. let minProjectWidth2 = camTangent.x * minThick_ + camTangent.y * minWidth_
  860. minProjectWidth = Math.min(minProjectWidth1, minProjectWidth2)
  861. maxProjectWidth = Math.max(maxProjectWidth1, maxProjectWidth2)
  862. let a = (camTangent.x + camTangent.y) * maxWidth
  863. //console.log('diffaaaaaa',maxProjectWidth,a, box.sid)
  864. maxX = THREE.MathUtils.clamp((projectWidth - minThick_ * camTangent.y) / camTangent.x, minThick_, maxWidth_) //可得x的最大值(假设y为最小值)
  865. maxY = THREE.MathUtils.clamp((projectWidth - minThick_ * camTangent.x) / camTangent.y, minThick_, maxWidth_) //可得y的最大值(假设x为最小值)
  866. minX = THREE.MathUtils.clamp((projectWidth - maxWidth_ * camTangent.y) / camTangent.x, minThick_, maxWidth_)
  867. minY = THREE.MathUtils.clamp((projectWidth - maxWidth_ * camTangent.x) / camTangent.y, minThick_, maxWidth_)
  868. }
  869. /*
  870. let maxX = projectWidth / camTangent.x //可得x的最大值(假设y为0)
  871. let maxY = projectWidth / camTangent.y //可得y的最大值(假设x为0)
  872. */
  873. //判断方向
  874. let o = { box, projectWidth, camTangent, maxProjectWidth, minProjectWidth, dis, maxX, maxY, minX, minY }
  875. if (config.atWall > 0 /* isType(box.category,battery) || isType(box.category,air) */) {
  876. //为了获取朝向
  877. o.xWidthPossible = -Math.abs(projectWidth - camTangent.x * maxWidth - camTangent.y * minWidth)
  878. o.yWidthPossible = -Math.abs(projectWidth - camTangent.x * minWidth - camTangent.y * maxWidth)
  879. //在接近45度时容易不准。另外如果被遮住一部分更会错,因此尽量不让被遮住的匹配
  880. }
  881. return o
  882. }
  883. let getPoseScore = (boxposes, boxType) => {
  884. let score = 0
  885. const minDis = 1.5
  886. /* if (boxposes[0].box.sid == 'pano12-13' && boxposes[1].box.sid == 'pano8-6') {
  887. console.log(4)
  888. } */
  889. boxposes.forEach(pose => {
  890. //pose.lowR = pose.dis < minDis ? Math.pow(THREE.MathUtils.smoothstep(pose.dis / minDis, 0, 1),2) : 1 //太近的话误差大
  891. pose.lowR = pose.dis < minDis ? Math.pow(pose.dis / minDis, 1.4) : 1 //太近的话误差大
  892. if (pose.projectWidth > pose.maxProjectWidth) {
  893. score += Math.pow((pose.projectWidth / pose.maxProjectWidth - 1) * pose.lowR, 2) * 500 //超过的话数字较大所以乘的数小一些
  894. } else if (/* isSingle && */ pose.projectWidth < pose.minProjectWidth) {
  895. score += Math.pow((pose.minProjectWidth / pose.projectWidth - 1) * pose.lowR, 2) * 500
  896. }
  897. let { min, max } = standards[boxType].widthNormal
  898. if ((standards[boxType].atWall == 1 && min < 0.3) || (boxposes.length == 2 && boxType == 'battery')) {
  899. let { min, max } = standards[boxType].widthNormal
  900. //let r = Math.max(0.001, (pose.projectWidth - min) / (max - min))
  901. let diff = max - min
  902. let r = math.linearClamp(pose.projectWidth, min, min + diff * 0.5, 600, 0)
  903. //if(boxposes.length == 2 && boxType == 'battery'){//由于battery经常出现遮挡,导致方向出错,因此尽量不匹配projectWidth较短的,尽管这本有可能是对的
  904. score += r
  905. //}
  906. /* if (min < 0.3 && r < 0.5) {
  907. //从贴近墙面的位置看侧面的话,容易被挡住,不准,尤其是电箱
  908. score += ((max - min) / r / min) * 5
  909. } */
  910. }
  911. })
  912. score = Math.min(score, 1300) //压低一点,因为得的宽度可能不准
  913. if (boxposes.length == 2) {
  914. //每一个方向对应有四个方向(每个象限一个)看到的projectWidth应该接近。
  915. //先把camTangent转化为第一个象限的
  916. let camTangent0 = new THREE.Vector2(Math.abs(boxposes[0].camTangent.x), Math.abs(boxposes[0].camTangent.y))
  917. let camTangent1 = new THREE.Vector2(Math.abs(boxposes[1].camTangent.x), Math.abs(boxposes[1].camTangent.y))
  918. let a = camTangent0.dot(camTangent1)
  919. if (a > 0.8) {
  920. //WcLVXvmV9AU
  921. //0.9: 25度之内. 0.8: 36.8度之内
  922. let diff = Math.abs(boxposes[0].projectWidth - boxposes[1].projectWidth)
  923. boxposes.score2 = a * diff * 1300 * boxposes[0].lowR * boxposes[1].lowR
  924. score += boxposes.score2
  925. //console.warn('在同一个方向看到的projectWidth应该接近。 ', diff)
  926. }
  927. boxposes.camTangentCos = a
  928. }
  929. //要不要加上minX等的差距?
  930. score = Math.min(score, 1200)
  931. return -score
  932. }
  933. let getBoxSize = info => {
  934. if (info.boxType == 'groundBar') {
  935. console.log(1)
  936. }
  937. if (info.size) return
  938. //console.warn('开始算 ' + info.name)
  939. let exStr = '',
  940. warnStr = ''
  941. let x, y //求对角线的向量 x>0,y>0
  942. //假设盒子的长宽为x,y (x>0,y>0),视线切线单位向量为(k,m),投影距离:x'k+y'm.(x'是正负x,y'是正负y)
  943. //由于盒子的对角线有四个可选方向,(类似四个象限) 则需要能使投影距离最长的一个对角线向量。
  944. //如,当k<0,m>0时,要使xk+ym 最大,必有x<0,y>0. 故 x = -x', y = y', 故 投影距离:x'k+y'm = x(-k)+ym 。
  945. //故无论km的符号如何,只要变为正数,再去联立方程即可得xy。(相当于切线转到第一象限)
  946. //注:但是因为无法获取准确的投影距离(角平分线左右两边的端点到角平分线的距离不相等,垂足也无法确定),所以所算的误差非常大。
  947. if (info.name == 'pano6-13&pano4-13') {
  948. console.log(6)
  949. }
  950. let center = getBoxPos(info)
  951. let oriX, oriY
  952. if (info.predictSize) {
  953. ;(x = oriX = info.predictSize.x), (y = oriY = info.predictSize.y)
  954. } else {
  955. if (info.box1) {
  956. let x1 = info.boxposes[0].camTangent.x,
  957. x2 = info.boxposes[1].camTangent.x,
  958. y1 = info.boxposes[0].camTangent.y,
  959. y2 = info.boxposes[1].camTangent.y,
  960. w1 = /* info.boxposes[0].projectWidth, */ THREE.MathUtils.clamp(info.boxposes[0].projectWidth, info.boxposes[0].minProjectWidth, info.boxposes[0].maxProjectWidth * 1.1), //校准。如果projectwidth不准那算出来更不准. 但XswQxwmn2ZC的里侧电池是前者更准
  961. w2 = /* info.boxposes[1].projectWidth */ THREE.MathUtils.clamp(info.boxposes[1].projectWidth, info.boxposes[1].minProjectWidth, info.boxposes[1].maxProjectWidth * 1.1)
  962. //如果识别到柜门上,(柜体被遮住了),整体中心就会在柜门上,且厚度小于真实值。
  963. if (x1 == 0) {
  964. y = w1
  965. x = (w2 - y2 * y) / x2
  966. } else {
  967. //联立方程得:
  968. y = (w2 - (x2 / x1) * w1) / (y2 - (x2 / x1) * y1)
  969. x = (w1 - y1 * y) / x1
  970. }
  971. //console.log('xy', { x, y })
  972. ;(x < 0.3 || x > 1.4) && (exStr += ' x:' + math.toPrecision(x, 2))
  973. ;(y < 0.3 || y > 1.4) && (exStr += ' y:' + math.toPrecision(y, 2))
  974. if (y < 0 || x < 0) {
  975. //console.log('<0 ?????????')
  976. warnStr = x < 0 ? 'x<0!' : 'y<0!'
  977. }
  978. ;(oriX = x), (oriY = y)
  979. } else {
  980. //single pano data
  981. //将maxX maxY 限定在标准范围内
  982. if (info.xProp) {
  983. let widthValue = standards[info.boxType].width
  984. let thickValue = standards[info.boxType].thick
  985. let maxX, maxY, minX, minY
  986. if (info.xProp == 'width') {
  987. /* x = oriX = THREE.MathUtils.clamp(info.boxposes[0].maxX, widthValue.min, widthValue.max)
  988. y = oriY = THREE.MathUtils.clamp(info.boxposes[0].maxY, thickValue.min, thickValue.max)
  989. */
  990. maxX = THREE.MathUtils.clamp(info.boxposes[0].maxX, widthValue.min, widthValue.max) //AG0bi2fhb3 需要将得到的minX等这四项都clamp后再平均
  991. maxY = THREE.MathUtils.clamp(info.boxposes[0].maxY, thickValue.min, thickValue.max)
  992. minX = THREE.MathUtils.clamp(info.boxposes[0].minX, widthValue.min, widthValue.max)
  993. minY = THREE.MathUtils.clamp(info.boxposes[0].minY, thickValue.min, thickValue.max)
  994. } else {
  995. /* x = oriX = THREE.MathUtils.clamp(info.boxposes[0].maxX, thickValue.min, thickValue.max)
  996. y = oriY = THREE.MathUtils.clamp(info.boxposes[0].maxY, widthValue.min, widthValue.max)
  997. */
  998. maxX = THREE.MathUtils.clamp(info.boxposes[0].maxX, thickValue.min, thickValue.max)
  999. maxY = THREE.MathUtils.clamp(info.boxposes[0].maxY, widthValue.min, widthValue.max)
  1000. minX = THREE.MathUtils.clamp(info.boxposes[0].minX, thickValue.min, thickValue.max)
  1001. minY = THREE.MathUtils.clamp(info.boxposes[0].minY, widthValue.min, widthValue.max)
  1002. }
  1003. x = oriX = (maxX + minX) / 2
  1004. y = oriY = (maxY + minY) / 2
  1005. } else {
  1006. //x = oriX = y = oriY = (min+max)/2
  1007. let standard = standards[info.boxType].widthNormal
  1008. x = oriX = THREE.MathUtils.clamp(info.boxposes[0].maxX, standard.min, standard.max)
  1009. y = oriY = THREE.MathUtils.clamp(info.boxposes[0].maxY, standard.min, standard.max)
  1010. }
  1011. }
  1012. //按正常来说,得到的x,y都应>0,但是由于箱子会被遮挡,导致投影宽度比真实的小,算出的也不准,可能是负数
  1013. //所以手动将过小的宽度矫正
  1014. }
  1015. /* if(info.name == "pano2-6"){
  1016. console.log(7)
  1017. } */
  1018. let height
  1019. if (standards[info.boxType].bottom) {
  1020. //悬挂的
  1021. //挂式空调最好把长宽固定。 不过极少出错
  1022. //center.y -= 0.1 //很可能过高
  1023. height = standards[info.boxType].height.standard
  1024. getBoxBtm(info)
  1025. if (height) {
  1026. let d = center.y - info.btmPos.y
  1027. center.y -= THREE.MathUtils.clamp((d - height / 2) / 2, -0.1, 0.1) //如果中心点到底部的距离和height的一半不同,中心点移动差值的一半
  1028. } else {
  1029. let btmY = info.btmPos.y
  1030. /* let ys = [info.btmPos.y]//info.btmPos.y蛮不准的
  1031. if(info.box0){
  1032. ys.push(info.box0.btmPos.y)
  1033. }
  1034. if(info.box1){
  1035. ys.push(info.box1.btmPos.y)
  1036. }
  1037. btmY = ys.reduce((w,c)=>{return w+c},0)
  1038. btmY/=ys.length //平均 */
  1039. height = (center.y - btmY) * 2
  1040. }
  1041. } else {
  1042. if (!info.topPos) getBoxTop(info)
  1043. height = info.topPos.y - groundY
  1044. }
  1045. let o = restrictSize(x, height, y, info)
  1046. ;(x = o.x), (height = o.y), (y = o.z)
  1047. if (standards[info.boxType].widthSame) {
  1048. x = y = (x + y) / 2
  1049. }
  1050. info.size = new THREE.Vector3(x, height, y)
  1051. info.sizeAdjust = Math.pow(Math.abs(x - oriX), 1.3) + Math.pow(Math.abs(y - oriY), 1.3) //计算得到的值和标准值之间的差距,可以反映该info的匹配分值
  1052. if (info.sizeAdjust) info.score = (info.score || 0) - Math.min(info.sizeAdjust * 100, 400)
  1053. ;(info.size.oriX = oriX), (info.size.oriY = oriY)
  1054. ;(info.exStr = exStr), (info.warnStr = warnStr)
  1055. }
  1056. let restrictSize = (x, y, z, info) => {
  1057. let s
  1058. let { xProp, yProp } = info
  1059. if (xProp != void 0) {
  1060. var { min, max } = standards[info.boxType][xProp]
  1061. x = THREE.MathUtils.clamp(x, min, max)
  1062. var { min, max } = standards[info.boxType][yProp]
  1063. z = THREE.MathUtils.clamp(z, min, max)
  1064. s = true
  1065. }
  1066. if (!s) {
  1067. var { min, max } = standards[info.boxType].widthNormal
  1068. x = THREE.MathUtils.clamp(x, min, max)
  1069. z = THREE.MathUtils.clamp(z, min, max)
  1070. }
  1071. var { min, max } = standards[info.boxType].height
  1072. y = THREE.MathUtils.clamp(y, min, max)
  1073. return { x, y, z }
  1074. }
  1075. let getMixBox = (box0, box1) => {
  1076. //重叠部分
  1077. let box = new THREE.Box2()
  1078. box.min.set(Math.max(box0.min.x, box1.min.x), Math.max(box0.min.y, box1.min.y))
  1079. box.max.set(Math.min(box0.max.x, box1.max.x), Math.min(box0.max.y, box1.max.y))
  1080. return box
  1081. }
  1082. let getLeftRight = boxArr => {
  1083. //获取pano的boxes中最左和最右的bbox.x
  1084. let lefts = boxArr.map(e => e.bbox2[0])
  1085. let rights = boxArr.map(e => e.bbox2[2])
  1086. lefts.sort((a, b) => getBbox2Diff(a, b))
  1087. rights.sort((a, b) => getBbox2Diff(b, a))
  1088. let leftX = lefts[0] //最左
  1089. let rightX = rights[0] //最右
  1090. return {
  1091. leftX,
  1092. rightX,
  1093. }
  1094. }
  1095. ;(global.searchCount1 = 0), (global.escapeCount1 = 0)
  1096. let searchPair = (beginItem, group0_, group1_, parentPairs, resultPairs, evaluateFun, minScore) => {
  1097. //配对结果个数为n!,其中n是每组的元素个数。注意当n=10时,已经有40320个,非常恐怖。
  1098. let pair = [],
  1099. parentExit = !!parentPairs
  1100. let removeParent = () => {
  1101. //元结点裂变出多个,来装新的pair
  1102. if (parentExit) {
  1103. let i = resultPairs.indexOf(parentPairs)
  1104. resultPairs.splice(i, 1)
  1105. parentExit = false
  1106. }
  1107. }
  1108. if (!parentPairs) {
  1109. //首次
  1110. if (group0_.length == 0 || group1_.length == 0) return
  1111. //保证第一个的个数<=第二个,否则第一组多出来的永远匹配不上
  1112. if (group0_.length > group1_.length) {
  1113. let t = group0_
  1114. group0_ = group1_
  1115. group1_ = t
  1116. }
  1117. beginItem = group0_[0]
  1118. let complex = Object.keys(boxFrame.datas).length
  1119. if (complex < 10) evaluateFun = null
  1120. else minScore = math.linearClamp(complex, 10, 80, -4000, -500)
  1121. //console.log('searchPair length',group0_.length,group1_.length)
  1122. }
  1123. searchCount1++
  1124. for (let j = 0; j < group1_.length; j++) {
  1125. pair = [beginItem, group1_[j]]
  1126. //if(pair[0].sid == 'void' || pair[1].sid == 'void')continue
  1127. let evaluate
  1128. if (evaluateFun /* && !(pair[0].sid == 'void' || pair[1].sid == 'void') */) {
  1129. evaluate = evaluateFun(pair[0], pair[1])
  1130. if (evaluate == void 0 || evaluate.score <= minScore) {
  1131. //console.log('因为评估出匹配可能性低所以跳过',pair[0],pair[1],evaluate)
  1132. escapeCount1++
  1133. continue
  1134. }
  1135. }
  1136. let newPairs //用来存放该组pair
  1137. if (parentPairs) {
  1138. removeParent()
  1139. newPairs = parentPairs.slice(0) //复制
  1140. newPairs.push(pair)
  1141. } else {
  1142. newPairs = [pair] //新的容器
  1143. }
  1144. resultPairs.push(newPairs)
  1145. let newGroup0 = group0_.slice(0)
  1146. let newGroup1 = group1_.slice(0)
  1147. let index = newGroup0.indexOf(pair[0])
  1148. newGroup0.splice(index, 1)
  1149. index = newGroup1.indexOf(pair[1])
  1150. newGroup1.splice(index, 1)
  1151. if (newGroup0.length > 0 && newGroup1.length > 0) {
  1152. searchPair(newGroup0[0], newGroup0, newGroup1, newPairs, resultPairs, evaluateFun, minScore)
  1153. }
  1154. }
  1155. }
  1156. //如果第一个元素就和后面所有的都不匹配,就直接返回了怎么办?
  1157. export default class PanoBoxFrame extends THREE.Group {
  1158. constructor(player_, ifAnalyze, dataList) {
  1159. super()
  1160. this.clear()
  1161. player = player_
  1162. player.model.add(this)
  1163. this.ifAnalyze = ifAnalyze
  1164. this.wireframes = new THREE.Object3D()
  1165. this.wireframes.name = 'wireframes'
  1166. this.add(this.wireframes)
  1167. this.matchScoreMap = {}
  1168. this.bindEvents()
  1169. meshGroup = new THREE.Object3D()
  1170. meshGroup.name = 'testBox'
  1171. this.add(meshGroup)
  1172. this.compute(dataList)
  1173. }
  1174. async compute(dataList) {
  1175. startTime = Date.now()
  1176. this.datas = {}
  1177. this.datasMixed = {}
  1178. this.boxesSolid = boxesSolid
  1179. let metadata = player.$app.store.getValue('metadata') //await player.$app.resource.metadata()
  1180. isLaser = metadata.sceneFrom == 'laser'
  1181. let compu = 0
  1182. let beginCompute = () => {
  1183. //获取匹配分数
  1184. let getMatchScore = (box0, box1, { isSingle, center, onlyGet, dontCheckDis } = {}) => {
  1185. let name0 = box0.sid + '&' + box1.sid
  1186. let name1 = box1.sid + '&' + box0.sid
  1187. let boxType = getBoxType(box0)
  1188. let matchInfo0 = this.matchScoreMap[boxType][name0]
  1189. let matchInfo1 = this.matchScoreMap[boxType][name1]
  1190. let matchInfo = matchInfo0 || matchInfo1
  1191. if (onlyGet) return matchInfo
  1192. let name
  1193. if (!matchInfo) {
  1194. name = name0
  1195. matchInfo = { name, box0, box1, center }
  1196. this.matchScoreMap[boxType][name] = matchInfo
  1197. } else {
  1198. return matchInfo
  1199. }
  1200. if (name == 'pano6-9&pano8-4') {
  1201. console.log(5)
  1202. }
  1203. getBoxBase(box0)
  1204. getBoxBase(box1)
  1205. let A = box0.pano.position.clone()
  1206. let B = box1.pano.position.clone()
  1207. let AB = new THREE.Vector3().subVectors(B, A)
  1208. let AB2d = new THREE.Vector2(AB.x, AB.z).normalize()
  1209. let AP12d = center ? new THREE.Vector2(center.x - A.x, center.z - A.z).normalize() : new THREE.Vector2(box0.centerDir.x, box0.centerDir.z).normalize()
  1210. let BP22d = center ? new THREE.Vector2(center.x - B.x, center.z - B.z).normalize() : new THREE.Vector2(box1.centerDir.x, box1.centerDir.z).normalize()
  1211. let angleA = Math.acos(AB2d.dot(AP12d))
  1212. let angleB = Math.PI - Math.acos(AB2d.dot(BP22d))
  1213. let score = 100,
  1214. str = []
  1215. if (angleA + angleB > Math.PI + 0.2) {
  1216. //无交点(比180大是因为中心角度有误差,所以给一定的容错)
  1217. //console.log(`${panoId0}的第${box0.index}个与${panoId1}的第${box1.index}个因角度大于180度 不匹配`)
  1218. return Object.assign(matchInfo, { score: -5000, str: ['angle>180'] })
  1219. }
  1220. if (box0.type != box1.type) {
  1221. return Object.assign(matchInfo, { score: -5000, str: ['typeNotSame'] })
  1222. }
  1223. if (matchInfo.dirAngleXZ == void 0) {
  1224. matchInfo.dirAngleXZ = THREE.MathUtils.radToDeg(Math.acos(AP12d.dot(BP22d))) //需要尽量接近90度算出来的交点会比较准
  1225. matchInfo.minAng = Math.min(180 - matchInfo.dirAngleXZ, matchInfo.dirAngleXZ) //角度小的getIntersect2容易算不准
  1226. if (isSingle) {
  1227. let bestDisSquared = 2
  1228. //单个匹配单个,而非多个匹配多个(没有固定到两个漫游点),所以可以直接寻找最优角度
  1229. score += Math.sin(THREE.MathUtils.degToRad(matchInfo.dirAngleXZ)) * 300
  1230. score += matchInfo.dirAngleXZ //另外角度越大越不容易偏向一边
  1231. score -= Math.abs(getBoxPos(box0).distanceToSquared(box0.pano.position) - bestDisSquared) * 10
  1232. score -= Math.abs(getBoxPos(box1).distanceToSquared(box1.pano.position) - bestDisSquared) * 10
  1233. }
  1234. }
  1235. let shinkRatio = 1
  1236. let btmPos0 = box0.btmPos || box0.btmPosPredict //fire类型先用btmPosPredict,测定groundY后才有btmPos
  1237. let btmPos1 = box1.btmPos || box1.btmPosPredict
  1238. if (!dontCheckDis) {
  1239. //let r = box0.boxType == 'air' ? 1 : box0.boxType == 'cabinet' ? 0.9 : 0.7 //随着宽度增加而降低
  1240. let r = THREE.MathUtils.clamp(0.8 / standards[boxType].widthNormal.max, 0.6, 2) //随着宽度增加而降低 UWrshepp0G5的fire
  1241. if (!standards[boxType].bottom && btmPos0 && btmPos1) {
  1242. //注:挂空调不应使用btmPosPredict
  1243. let d = btmPos0.distanceToSquared(btmPos1)
  1244. matchInfo.btmPosPreDis = d
  1245. score -= d * 1300 * r * shinkRatio
  1246. if (box1.topPos) {
  1247. let a = box0.topPos.distanceToSquared(box1.topPos)
  1248. matchInfo.topPosPreDis = a
  1249. let u = a * 700 * r * shinkRatio
  1250. let AP0 = new THREE.Vector2(btmPos0.x - A.x, btmPos0.z - A.z).lengthSq()
  1251. let AP1 = new THREE.Vector2(btmPos1.x - B.x, btmPos1.z - B.z).lengthSq()
  1252. if (AP0 < 0.4 || AP1 < 0.4) u *= 0.3 //太近
  1253. score -= u
  1254. }
  1255. } else if (box0.posAtWall && box1.posAtWall) {
  1256. //
  1257. let d = box0.posAtWall.distanceToSquared(box1.posAtWall)
  1258. matchInfo.wallPosPreDis = d
  1259. score -= d * 200 * r //墙面不准所以分低 ftMTQIrs79
  1260. d = box0.btmPosOri.distanceToSquared(box1.btmPosOri) //还是加一下
  1261. matchInfo.btmPosPreDis = d
  1262. score -= d * 200 * r * shinkRatio
  1263. /* let h0 = box0.topPos.y - box0.btmPos.y
  1264. let h1 = box1.topPos.y - box1.btmPos.y
  1265. score -= Math.abs(h0-h1) * 3000 * r * shinkRatio //高度差 倾斜角度大的不准
  1266. */
  1267. }
  1268. }
  1269. if (!matchInfo.center) {
  1270. let o = getIntersect2(A, box0.centerDir, B, box1.centerDir)
  1271. matchInfo.center = o.pos3d.clone()
  1272. /* let o2 = math.getLineIntersect({ A, B, p1: A.clone().add(box0.centerDir), p2:B.clone().add(box1.centerDir) })
  1273. matchInfo.center2 = o2.pos3d.clone() */
  1274. /* if (name == "pano16-4&pano18-5") {
  1275. addLine(A, box0.centerBtmDir, 10), addLine(B, box1.centerBtmDir, 10)
  1276. } */
  1277. //验证是否漫游点到中心点的方向和centerDir一样
  1278. let dir0 = new THREE.Vector3().subVectors(o.pos3d, A).normalize()
  1279. let dir1 = new THREE.Vector3().subVectors(o.pos3d, B).normalize()
  1280. let sum = dir0.dot(box0.centerDir) + dir1.dot(box1.centerDir)
  1281. let wrongDir = sum < 1.95
  1282. score -= (2 - sum) * 10000
  1283. if (wrongDir) {
  1284. str.push('wrongDir')
  1285. return Object.assign(matchInfo, { score: score - 5000, str })
  1286. }
  1287. if (!dontCheckDis && !standards[boxType].bottom && box0.btmPos && box1.btmPos) {
  1288. //墙壁位置不准所以不用 KK-ftMTQIrs79
  1289. let p0 = new THREE.Vector2(box0.btmPos.x, box0.btmPos.z)
  1290. let p1 = new THREE.Vector2(box1.btmPos.x, box1.btmPos.z)
  1291. let p = new THREE.Vector2(matchInfo.center.x, matchInfo.center.z)
  1292. let dis = p0.distanceToSquared(p) + p1.distanceToSquared(p)
  1293. let s = math.linearClamp(matchInfo.minAng, 0, 20, 0, 1)
  1294. score -= dis * 1500 * s //如果距离较远就说明算的center误差大,不可信。可能有一个框不准确
  1295. matchInfo.centerDrift = dis
  1296. }
  1297. getBoxBtm(matchInfo)
  1298. let cr //getIntersect2结果的权重
  1299. if (standards[box0.boxType].atWall == 1) {
  1300. cr = math.linearClamp(matchInfo.minAng, 2, 15, 0, 1) //墙壁误差大,所以尽量完全依赖cIntersect。。。后期如果该墙壁校准了可以调整
  1301. } else {
  1302. cr = math.linearClamp(matchInfo.minAng, 2, 20, 0, 0.4)
  1303. }
  1304. let predict0 = (!standards[boxType].bottom && box0.btmPos) || box0.posAtWall || matchInfo.topPos //在墙上的除非角度小,否则不考虑cIntersect
  1305. let predict1 = (!standards[boxType].bottom && box1.btmPos) || box1.posAtWall || matchInfo.topPos
  1306. //相对来说btmPos要比center准一点?因为center有在两个维度上的误差
  1307. const btmRatio = 0.5
  1308. let cIntersect = new THREE.Vector3().addVectors(matchInfo.center.clone().multiplyScalar(1 - btmRatio), matchInfo.btmPos.clone().multiplyScalar(btmRatio)).setY(o.pos3d.y)
  1309. if (predict0 && predict1) {
  1310. matchInfo.center = new THREE.Vector3()
  1311. .addVectors(
  1312. cIntersect.clone().multiplyScalar(cr),
  1313. predict0
  1314. .clone()
  1315. .add(predict1)
  1316. .multiplyScalar((1 / 2) * (1 - cr))
  1317. )
  1318. .setY(o.pos3d.y)
  1319. } else {
  1320. matchInfo.center = cIntersect
  1321. }
  1322. matchInfo.cIntersect = cIntersect
  1323. //addLabel(matchInfo.center, matchInfo.name + '-c')
  1324. }
  1325. getBoxType(matchInfo)
  1326. /* if (matchInfo.boxType != box0.type || matchInfo.boxType != box1.type) {
  1327. ;(score -= 1000), str.push('typeNotSame2')
  1328. } */
  1329. {
  1330. let vec0 = new THREE.Vector3().subVectors(box0.pano.position, matchInfo.center)
  1331. let vec1 = new THREE.Vector3().subVectors(box1.pano.position, matchInfo.center)
  1332. if (vec0.x * vec1.x > 0 && vec0.z * vec1.z > 0) {
  1333. //同一个象限(center会偏向一侧)
  1334. score -= 200
  1335. }
  1336. }
  1337. if (!safeBound.containsPoint(matchInfo.center)) {
  1338. let dis = safeBound.distanceToPoint(matchInfo.center)
  1339. //console.log(`${panoId0}的第${box0.index}个与${panoId1}的第${box1.index}个因中心点在bounding外不匹配`, center, 'dis: ' + dis)
  1340. ;(score -= 1000 * dis * dis), str.push('outsideBound')
  1341. Object.assign(matchInfo, { score, str, center: matchInfo.center, disToBound: dis })
  1342. if (dis > 0.5) return matchInfo
  1343. }
  1344. //检查宽度
  1345. let boxposes
  1346. let checkWidth = () => {
  1347. boxposes = []
  1348. ;[box0, box1].forEach(box => {
  1349. let pose = getBoxPoseByPos(box, matchInfo.center)
  1350. boxposes.push(pose)
  1351. //如果超出标准,基本上这二者不匹配;但过小的话,有可能是被遮挡所以残缺,因此不予过滤
  1352. })
  1353. }
  1354. checkWidth()
  1355. score += getPoseScore(boxposes, boxType /* isSingle */) //根据投影信息预测的长度再得匹配分数
  1356. compu++
  1357. return Object.assign(matchInfo, { score: score, str, /* diffHalfHeight, */ boxposes })
  1358. }
  1359. this.rows = {}
  1360. /* let getchainNext = (left, end, chain, boxes) => {
  1361. chain.push(left)
  1362. if (left == end) return boxes.chains.push(chain)
  1363. let nodes = boxes.relationships.filter(pair => pair.includes(left))
  1364. let rights = nodes.map(pair => pair.find(e => e != left))
  1365. rights = rights.filter(e => !chain.includes(e) && boxes.indexOf(e) > boxes.indexOf(left))
  1366. rights.forEach(right => {
  1367. getchainNext(right, end, chain.slice(), boxes)
  1368. })
  1369. } */
  1370. let getPanoBigRowBox = (panoBoxes, { reason = 'row' } = {}) => {
  1371. //将一个pano中的所有boxes分组,识别哪些是一排的。也可用于识别融合
  1372. let pano = panoBoxes[0].pano
  1373. const category = panoBoxes[0].category
  1374. let type = category + '|' + reason
  1375. this.rows[type] || (this.rows[type] = {})
  1376. if (this.rows[type][pano.id]) return this.rows[type][pano.id]
  1377. let bigBoxes
  1378. let bigBox = {
  1379. sid: 'pano' + pano.id + (reason == 'mix' ? '-mix' : '-row'),
  1380. pano,
  1381. category: reason == 'mix' ? category : 'rowBigBox',
  1382. boxType: reason == 'mix' ? panoBoxes[0].boxType : 'rowBigBox',
  1383. }
  1384. let rows = []
  1385. for (let i = 0; i < panoBoxes.length; i++) {
  1386. let box0 = panoBoxes[i]
  1387. getBoxBase(box0)
  1388. let [left0, right0] = [box0.bbox2[0], box0.bbox2[2]]
  1389. for (let j = i + 1; j < panoBoxes.length; j++) {
  1390. let box1 = panoBoxes[j]
  1391. getBoxBase(box1)
  1392. if (box0.boxType != box0.boxType) continue //类型不同
  1393. let [left1, right1] = [box1.bbox2[0], box1.bbox2[2]]
  1394. let d1 = getBbox2Diff(left1, right0),
  1395. d2 = getBbox2Diff(left1, left0),
  1396. d3 = getBbox2Diff(left0, right1)
  1397. if (box0.sid == 'pano2-4' && box1.sid == 'pano2-5') {
  1398. console.log(9)
  1399. }
  1400. const min = reason == 'mix' ? 0.004 : 0.003 //mix代表寻找分裂的重新融合到一起
  1401. if ((d1 <= min && d2 >= min) || (d3 <= min && d2 <= min)) {
  1402. //边框交接
  1403. let atEdgeMight = left1 < 0.002 && right0 > 0.998 ? [left1, right0] : left0 < 0.002 && right1 > 0.998 ? [left0, right1] : null //有在全景图的边界的可能性
  1404. //if (reason == 'mix' && box0.category == typeNames.cabinet && !atEdgeMight) continue //柜子容易并排,尽量不融合 //再看,啥意思,没懂
  1405. if (reason == 'mix' && !atEdgeMight) continue //不在边缘
  1406. const { max } = standards[box0.boxType].widthNormal //standards[box0.btmPos ? category : 'air-hanging'].widthNormal
  1407. const tolerate = max * max * (reason == 'mix' ? 0.7 : 1.8) //yDCiaTQvRYn:row不能低于1.5
  1408. let p0 = standards[box0.boxType].atWall == 1 ? box0.posAtWall : reason == 'mix' ? box0.btmPosOri || box0.btmPosPredict : box0.btmPos
  1409. let p1 = standards[box1.boxType].atWall == 1 ? box1.posAtWall : reason == 'mix' ? box1.btmPosOri || box1.btmPosPredict : box1.btmPos
  1410. //let p0 = box0.type == 'air-hanging' ? box0.posAtWall : reason == 'mix' ? box0.btmPosOri : box0.btmPos
  1411. //let p1 = box1.type == 'air-hanging' ? box1.posAtWall : reason == 'mix' ? box1.btmPosOri : box1.btmPos
  1412. let dis = p0.distanceToSquared(p1)
  1413. if (reason == 'mix') {
  1414. let allY = box0.bbox2[3] - box0.bbox2[1] + (box1.bbox2[3] - box1.bbox2[1]) //各自高度和
  1415. let wholeY = Math.max(box0.bbox2[3], box1.bbox2[3]) - Math.min(box0.bbox2[1], box1.bbox2[1]) //总跨越高度
  1416. let coverY = allY - wholeY //重合区域的y高度,可为负数
  1417. let disY = (1 - coverY / wholeY + (wholeY - coverY) * 3) * 4 * tolerate //既要考虑占比也要考虑差值
  1418. dis += disY //SGyhEzZNGP9案例:虽然是atEdge但并不应该融合,便通过disY来阻挡 ; MW6MEeCOy9Y:pano16-15
  1419. //console.log('disY',disY, box0.sid, box1.sid )
  1420. let atEdgePossib = atEdgeMight ? 0.002 / (atEdgeMight[0] + (1 - atEdgeMight[1])) : 0 // 两条线越接近越可能融合
  1421. atEdgePossib = Math.min(6, atEdgePossib) //原本计算得 min:1, max:Infinity
  1422. dis -= atEdgePossib * tolerate //给点点优势
  1423. }
  1424. /* if(box0.sid == "pano2-0"){
  1425. console.log('dis',dis,'tolerate',tolerate,[box0, box1],disY)
  1426. }
  1427. if (box0.sid == 'pano2-1' && box1.sid == 'pano2-4') {
  1428. reason == 'mix' && console.log(dis, tolerate, box0.sid, box1.sid)
  1429. }*/
  1430. if (dis < tolerate) {
  1431. //reason == 'mix' && console.log('-------------------')
  1432. common.pushToGroupAuto([box0, box1], rows)
  1433. }
  1434. }
  1435. }
  1436. }
  1437. //一排箱子的角度范围不可超过180度,因为不可能站在箱子上拍,所以超过的话肯定有边缘的不在这一排中。
  1438. //可判断边缘箱子的是否角度偏大,一般中间的被遮挡所以偏小
  1439. rows.forEach(boxes => {
  1440. //从左到右排序
  1441. boxes.sort((a, b) => {
  1442. //但因有的box跨越到别的box区域,所以这个顺序不准确
  1443. return getBbox2Diff(a.bbox2CenterX, b.bbox2CenterX)
  1444. })
  1445. })
  1446. //去除不在一条直线上的连接. 当bound超出后就断开
  1447. if (reason == 'row') {
  1448. rows.slice(0).forEach(boxes => {
  1449. if (boxes.length >= 2) {
  1450. let removes = [],
  1451. bound = new THREE.Box2(),
  1452. size = new THREE.Vector2(),
  1453. maxW = 0.6
  1454. for (let i = 0, j = boxes.length; i < j; i++) {
  1455. let box = boxes[i]
  1456. let pos2d = new THREE.Vector2(box.btmPos.x, box.btmPos.z)
  1457. bound.expandByPoint(pos2d)
  1458. bound.getSize(size)
  1459. let min = Math.min(size.x, size.y)
  1460. if (min > maxW) {
  1461. removes.push([boxes[i], boxes[i - 1]])
  1462. bound = new THREE.Box2()
  1463. bound.expandByPoint(pos2d)
  1464. console.log('removes', size)
  1465. }
  1466. //console.log('removes',k, box1.sid)
  1467. }
  1468. if (removes.length) {
  1469. console.log(
  1470. '去除错误row连接',
  1471. removes.map(e => e.map(a => a.sid))
  1472. )
  1473. let { newGroups } = common.disconnectGroup(removes, rows)
  1474. //if(newGroups.length>1){//分裂成多组了,重新计算
  1475. // console.log(newGroups)
  1476. //}
  1477. }
  1478. }
  1479. })
  1480. rows.forEach(boxes => {
  1481. //从左到右重新排序
  1482. boxes.sort((a, b) => {
  1483. //但因有的box跨越到别的box区域,所以这个顺序不准确
  1484. return getBbox2Diff(a.bbox2CenterX, b.bbox2CenterX)
  1485. })
  1486. })
  1487. }
  1488. rows.sort((a, b) => {
  1489. return b.length - a.length
  1490. }) //箱子数量从大到小排序
  1491. bigBoxes = rows.map((boxes, i) => {
  1492. let { leftX, rightX } = getLeftRight(boxes) //最左
  1493. let topY = boxes.slice().sort((a, b) => a.bbox2[1] - b.bbox2[1])[0].bbox2[1]
  1494. let btmY = boxes.slice().sort((a, b) => b.bbox2[3] - a.bbox2[3])[0].bbox2[3]
  1495. let rowBigBox = Object.assign({}, bigBox, {
  1496. boxes,
  1497. bbox2: [leftX, topY, rightX, btmY], //整排的bbox
  1498. left: boxes.find(e => e.bbox2[0] == leftX),
  1499. right: boxes.find(e => e.bbox2[2] == rightX),
  1500. })
  1501. let p0 = getBoxPos(rowBigBox.left)
  1502. let p1 = getBoxPos(rowBigBox.right)
  1503. let vec = new THREE.Vector2(p0.x - p1.x, p0.z - p1.z)
  1504. rowBigBox.k = Math.abs(vec.x / vec.y)
  1505. rowBigBox.predictLen = (rowBigBox.k > 1 ? Math.abs(vec.x) : Math.abs(vec.y)) + 0.6 //加入一个宽度
  1506. /* if(boxes.length <= boxes.relationships.length){//多条链(为了识别一个box嵌套多个的情况。不过后来在开头时处理了一部分)
  1507. boxes.chains = []
  1508. getchainNext(left,right,[], boxes )
  1509. let aveAngle = (getBbox2Diff(left.bbox2[2], left.bbox2[0]) + getBbox2Diff(right.bbox2[2], right.bbox2[0]) ) / 2 -0.01 //首尾的angle平均数。但如果这两个不准那就导致整体出错了
  1510. let middleAngle = getBbox2Diff(right.bbox2[0], left.bbox2[2])
  1511. let counts = boxes.chains.map(e=>e.length)
  1512. counts.sort((a,b)=>a-b)
  1513. let min = counts[0],max = counts[counts.length-1]
  1514. let r = [], cur = min;
  1515. while(cur<=max){
  1516. r.push({cur, diff:Math.abs((middleAngle / (cur-2) - aveAngle)}) //加 0.01是因为增加边缘
  1517. cur++
  1518. }
  1519. r.sort((a,b)=>a.diff-b.diff)
  1520. rowBigBox.predictBoxCount = r[0].cur
  1521. //---------
  1522. let goodCountChains = boxes.chains.filter(e=>e.length == rowBigBox.predictBoxCount)
  1523. if(goodCountChains.length == 1) rowBigBox.bestChain = goodCountChains[0]
  1524. else{
  1525. goodCountChains = goodCountChains.map((chain,i)=>{
  1526. let j = 1, diff=0 //中间的box的angle的方差
  1527. while(j<rowBigBox.predictBoxCount){
  1528. let angle = getBbox2Diff(chain[j].bbox2[2], chain[j].bbox2[0])
  1529. diff += Math.pow(angle - aveAngle, 2)
  1530. j++;
  1531. }
  1532. return {diff, chain}
  1533. })
  1534. goodCountChains.sort((a,b)=>a.diff-b.diff)
  1535. rowBigBox.bestChain = goodCountChains[0].chain
  1536. }
  1537. console.log('getChains',boxes.chains, 'predictBoxCount',rowBigBox.predictBoxCount, r)
  1538. } */
  1539. return rowBigBox
  1540. })
  1541. if (reason != 'mix') {
  1542. panoBoxes.forEach(box => {
  1543. //加入单个的
  1544. if (!rows.some(row => row.includes(box))) {
  1545. let boxBig = Object.assign({}, bigBox, {
  1546. bbox2: box.bbox2,
  1547. boxes: [box],
  1548. left: box,
  1549. right: box,
  1550. })
  1551. bigBoxes.push(boxBig)
  1552. }
  1553. })
  1554. }
  1555. //mix的之前的btm因pose错误而延伸了不对的depth所以不准
  1556. bigBoxes.forEach(bigBox => {
  1557. bigBox.sid += '-' + bigBox.boxes.map(e => e.index).join(',')
  1558. /* if (bigBox.sid == 'pano0-rowBigBox-1,0,2,4') {
  1559. console.log(3)
  1560. } */
  1561. if (reason == 'row') {
  1562. //取平均值
  1563. if (bigBox.boxes[0].btmPos) {
  1564. bigBox.btmPos = bigBox.boxes.reduce((w, c) => w.add(c.btmPos), new THREE.Vector3()).multiplyScalar(1 / bigBox.boxes.length)
  1565. //addLabel(bigBox.btmPos,'b_'+bigBox.sid, {bgcolor:'#f93',a:0.4})
  1566. }
  1567. if (bigBox.boxes[0].topPos) {
  1568. bigBox.topPos = bigBox.boxes.reduce((w, c) => w.add(c.topPos), new THREE.Vector3()).multiplyScalar(1 / bigBox.boxes.length)
  1569. }
  1570. if (bigBox.boxes[0].posAtWall) {
  1571. bigBox.posAtWall = bigBox.boxes.reduce((w, c) => w.add(c.posAtWall), new THREE.Vector3()).multiplyScalar(1 / bigBox.boxes.length)
  1572. }
  1573. }
  1574. //mix的需要合并后计算才准确
  1575. })
  1576. this.rows[type][pano.id] = bigBoxes //当前pano的所有row
  1577. return bigBoxes
  1578. }
  1579. /* let getPanoBoxAngleTrend = rowBox => {
  1580. //顺时针方向该pano的box角度范围是越来越大还是越来越小
  1581. let diffs = []
  1582. let angles = rowBox.boxes.map(box => getBbox2Diff(box.bbox2[2], box.bbox2[0]))
  1583. for (let i = 0, j = angles.length; i < j - 1; i++) {
  1584. //得所有相邻之间的差
  1585. let a0 = angles[i],
  1586. a1 = angles[i + 1]
  1587. diffs.push(a1 - a0)
  1588. }
  1589. diffs.sort((a, b) => a - b)
  1590. return diffs[Math.floor(diffs.length / 2)] //中位数
  1591. } */
  1592. /* let getBoxCount = (rowBigBox)=>{
  1593. return rowBigBox.predictBoxCount || rowBigBox.boxes.length
  1594. } */
  1595. let getReverseInfo = (rowBigBox0, rowBigBox1) => {
  1596. //两个row的方向对应
  1597. let reversed = false
  1598. let lefts = [rowBigBox0.left, rowBigBox1.left]
  1599. let rights = [rowBigBox0.right, rowBigBox1.right]
  1600. let dis0 = lefts[0].btmPos.distanceToSquared(lefts[1].btmPos)
  1601. let dis1 = rights[0].btmPos.distanceToSquared(rights[1].btmPos)
  1602. let dis2 = lefts[0].btmPos.distanceToSquared(rights[1].btmPos)
  1603. let dis3 = rights[0].btmPos.distanceToSquared(lefts[1].btmPos)
  1604. let posLeft2, posRight2
  1605. if (dis0 + dis1 > dis2 + dis3) {
  1606. //距离近的代表是同一端
  1607. reversed = true
  1608. posLeft2 = new THREE.Vector3().addVectors(lefts[0].btmPos, rights[1].btmPos).multiplyScalar(0.5)
  1609. posRight2 = new THREE.Vector3().addVectors(rights[0].btmPos, lefts[1].btmPos).multiplyScalar(0.5)
  1610. } else {
  1611. posLeft2 = new THREE.Vector3().addVectors(lefts[0].btmPos, lefts[1].btmPos).multiplyScalar(0.5)
  1612. posRight2 = new THREE.Vector3().addVectors(rights[0].btmPos, rights[1].btmPos).multiplyScalar(0.5)
  1613. }
  1614. let vec = new THREE.Vector2(posLeft2.x - posRight2.x, posLeft2.z - posRight2.z)
  1615. let k = Math.abs(vec.x / vec.y) //这个算斜率更准,但位置容易偏向一侧(可能用边缘的bbox算会好些?)
  1616. return { reversed, k }
  1617. }
  1618. let searchByRow = (groups, datas) => {
  1619. //先查找row,匹配row,再slice row的方法
  1620. this.matchScoreMap['rowBigBox'] = {}
  1621. let rowInfos = []
  1622. let getRowMatchInfo = (rowBigBox0, rowBigBox1, ignoreCountMatch) => {
  1623. //获取row间的匹配信息
  1624. //获取bigBox位置。由于一排的盒子比较长,中心方向误差大,所以采用先获取两边位置,再求中点的方法
  1625. //if (rowBigBox0.boxes.length != rowBigBox1.boxes.length && !ignoreCountMatch) return //太难了,不算不一样的情况了
  1626. let name = rowBigBox0.sid + '&' + rowBigBox1.sid
  1627. if (name in rowInfos) {
  1628. return rowInfos[name]
  1629. }
  1630. if (name == 'pano4-row-2,11,10,8,6&pano6-row-2,5,8,11') {
  1631. console.log(3)
  1632. }
  1633. if (rowBigBox0.boxes.length != rowBigBox1.boxes.length && !ignoreCountMatch) return
  1634. //if (getBoxCount(rowBigBox0) != getBoxCount(rowBigBox1) && getBoxCount(rowBigBox0) != 1 && getBoxCount(rowBigBox1) != 1)return
  1635. /* if (rowBigBox0.sid == 'pano0-row-1,2,6' && rowBigBox1.sid == 'pano2-row-0,2,6') {
  1636. console.log(4)
  1637. } */
  1638. let rowInfo
  1639. if (rowBigBox0.boxes.length > 1 && rowBigBox1.boxes.length > 1) {
  1640. //多对多,可以求两端的位置
  1641. let lefts = [rowBigBox0.left, rowBigBox1.left]
  1642. let rights = [rowBigBox0.right, rowBigBox1.right]
  1643. let leftInfo
  1644. let rightInfo
  1645. let info2 = getReverseInfo(rowBigBox0, rowBigBox1)
  1646. let len0 = rowBigBox0.predictLen, //长度应该接近
  1647. len1 = rowBigBox1.predictLen
  1648. let overLen = Math.abs(len0 - len1) /* / (rowBigBox0.boxes.length + rowBigBox1.boxes.length) * 5 */
  1649. if (overLen > 1) {
  1650. //console.warn('overLen> 1', overLen, rowBigBox0.sid, '和', rowBigBox1.sid)
  1651. return done()
  1652. }
  1653. if (info2.reversed) {
  1654. leftInfo = getMatchScore(lefts[0], rights[1], { isSingle: true })
  1655. rightInfo = getMatchScore(rights[0], lefts[1], { isSingle: true })
  1656. } else {
  1657. leftInfo = getMatchScore(lefts[0], lefts[1], { isSingle: true })
  1658. rightInfo = getMatchScore(rights[0], rights[1], { isSingle: true })
  1659. }
  1660. let posLeft = getBoxPos(leftInfo)
  1661. let posRight = getBoxPos(rightInfo)
  1662. if (!posLeft || !posRight || leftInfo.score < -4000 || rightInfo.score < -4000) {
  1663. return done() //漫游点重合、>180度会导致此问题
  1664. }
  1665. preDealBox(leftInfo)
  1666. //getBoxSize(leftInfo)
  1667. preDealBox(rightInfo)
  1668. //getBoxSize(rightInfo)
  1669. posLeft = getBoxPos(leftInfo)
  1670. posRight = getBoxPos(rightInfo)
  1671. //验证是否是垂直或水平
  1672. let vec = new THREE.Vector2(posLeft.x - posRight.x, posLeft.z - posRight.z)
  1673. let k = Math.abs(vec.x / vec.y)
  1674. if ((info2.k > 1 && k < 1) || (info2.k < 1 && k > 1)) {
  1675. console.error('请检查!info2.k > 1 && k < 1 || info2.k < 1 && k > 1', rowBigBox0.sid, '和', rowBigBox1.sid) //绘制的方向错误,尺寸错误
  1676. return done()
  1677. }
  1678. let wrongK = 0
  1679. if ((rowBigBox0.k > 1 && rowBigBox1.k < 1) || (rowBigBox0.k < 1 && rowBigBox1.k > 1)) {
  1680. wrongK = rowBigBox0.k / rowBigBox1.k
  1681. if (wrongK < 1) wrongK = 1 / wrongK
  1682. }
  1683. /*
  1684. let trend0 = getPanoBoxAngleTrend(rowBigBox0)
  1685. let trend1 = getPanoBoxAngleTrend(rowBigBox1)
  1686. let judgeReverse = () => { //这个方法有时不准
  1687. let disLeftSquared0 = new THREE.Vector2(posLeft.x - rowBigBox0.pano.position.x, posLeft.z - rowBigBox0.pano.position.z).lengthSq()
  1688. let disRightSquared0 = new THREE.Vector2(posRight.x - rowBigBox0.pano.position.x, posRight.z - rowBigBox0.pano.position.z).lengthSq()
  1689. let a = trend0 * (disLeftSquared0 - disRightSquared0)
  1690. if (a < 0 && Math.abs(a) > 0.1) return true
  1691. let posLeft2 = reversed ? posRight : posLeft, //反向过的对第二个漫游点来说左右是反的
  1692. posRight2 = reversed ? posLeft : posRight
  1693. let disLeftSquared1 = new THREE.Vector2(posLeft2.x - rowBigBox1.pano.position.x, posLeft2.z - rowBigBox1.pano.position.z).lengthSq()
  1694. let disRightSquared1 = new THREE.Vector2(posRight2.x - rowBigBox1.pano.position.x, posRight2.z - rowBigBox1.pano.position.z).lengthSq()
  1695. let b = trend1 * (disLeftSquared1 - disRightSquared1)
  1696. if (b < 0 && Math.abs(b) > 0.1) return true
  1697. }
  1698. if (leftInfo.score < -2000 || rightInfo.score < -2000 || judgeReverse()) {
  1699. //反向试试
  1700. leftInfo = getMatchScore(lefts[0], rights[1], { isSingle: true })
  1701. rightInfo = getMatchScore(rights[0], lefts[1], { isSingle: true })
  1702. posLeft = getBoxPos(leftInfo)
  1703. posRight = getBoxPos(rightInfo)
  1704. reversed = true //rowBigBox1 反向了
  1705. }
  1706. if (leftInfo.score < -2000 || rightInfo.score < -2000 || judgeReverse()) {
  1707. return console.log('getCenter ;两个方向都不符合', rowBigBox0.sid, rowBigBox1.sid)
  1708. } */
  1709. /*const maxK = Math.max(0.6 / Math.sqrt(rowBigBox0.boxes.length), 0.2) // 最大斜率
  1710. if (k < maxK && k > 1 / maxK) {
  1711. return //console.log('放弃,斜率', k)
  1712. } */
  1713. //横的话,按x从小到大,竖的按z从小到大
  1714. if ((k < 1 && posLeft.z > posRight.z) || (k > 1 && posLeft.x > posRight.x)) {
  1715. let temp = posRight
  1716. ;(posRight = posLeft), (posLeft = temp)
  1717. }
  1718. //addLabel(posLeft, 'left-' + rowBigBox0.pano.id + '&' + rowBigBox1.pano.id, { a: 0.1 })
  1719. //addLabel(posRight, 'right-' + rowBigBox0.pano.id + '&' + rowBigBox1.pano.id, { a: 0.1 })
  1720. /* if (rowBigBox0.pano.id + '&' + rowBigBox1.pano.id == '22&26') {
  1721. console.log(777)
  1722. } */
  1723. /* var line1 = LineDraw.createLine([posLeft, posRight])
  1724. meshGroup.add(line1) */
  1725. //根据btmPos矫正一下中心位置, 否则容易偏漫游点这一侧
  1726. let center = new THREE.Vector3().addVectors(posLeft, posRight).multiplyScalar(0.5)
  1727. center
  1728. .add(rowBigBox0.btmPos)
  1729. .add(rowBigBox1.btmPos)
  1730. .multiplyScalar(1 / 3)
  1731. let axis = k > 1 ? 'z' : 'x'
  1732. //posLeft[axis] = center[axis], posRight[axis] = center[axis]
  1733. let match = getMatchScore(rowBigBox0, rowBigBox1, { isSingle: true, center }) //是否预先传送center ?
  1734. //rowInfo.minAngs = [leftInfo.minAng , rightInfo.minAng]
  1735. /* if (match.name == 'pano4-row-6,4,1,3&pano0-row-0,1,4,5') {
  1736. console.log(8)
  1737. } */
  1738. let sc = match.score - overLen * 1000 - wrongK * 100 + leftInfo.score + rightInfo.score
  1739. if (sc < -4000) {
  1740. //console.log('放弃,匹配分过低,可能不是一组', rowBigBox0.sid, '和', rowBigBox1.sid, sc)
  1741. return done()
  1742. }
  1743. //console.log('getcenter', rowBigBox0.sid, '和', rowBigBox1.sid, overLen, match.score + overLen * 1000 + leftInfo.score + rightInfo.score)
  1744. rowInfo = {
  1745. rowBigBox0,
  1746. rowBigBox1,
  1747. match,
  1748. k,
  1749. posLeft,
  1750. posRight,
  1751. score: sc / 3 + 500, //700 + match.score*0.7 + (leftInfo.score + rightInfo.score)*0.3 ,
  1752. reversed: info2.reversed,
  1753. }
  1754. } else {
  1755. if (rowBigBox0.boxes.length == 1 && rowBigBox1.boxes.length == 1) {
  1756. rowInfo = getMatchScore(rowBigBox0.boxes[0], rowBigBox1.boxes[0]) //直接匹配box
  1757. } else {
  1758. //一对多。getMatchScore计算误差大(长度越长中心误差越大、宽度计算也误差大)所以再写点限制。直接使用btm来预测长度和位置似乎更准
  1759. let mulBoxRow = rowBigBox0.boxes.length > 1 ? rowBigBox0 : rowBigBox1
  1760. let singleBox = rowBigBox0.boxes.length == 1 ? rowBigBox0 : rowBigBox1
  1761. /* if(rowBigBox0.sid == "pano12-row-3" && rowBigBox1.sid == "pano0-row-3,1,0" ){
  1762. console.log(5)
  1763. } */
  1764. rowInfo = getMatchScore(rowBigBox0, rowBigBox1, { dontCheckDis: true }) //一对多 也可以根据方向检查距离,如仅检查z
  1765. rowInfo.k = mulBoxRow.k
  1766. if (rowInfo.center) {
  1767. rowInfo.center.add(getBoxPos(mulBoxRow)).multiplyScalar(0.5)
  1768. }
  1769. if (rowInfo.name == 'pano0-row-14&pano4-row-8,11') {
  1770. addLabel(rowInfo.center, 'c')
  1771. }
  1772. rowInfo.predictSize = rowInfo.k > 1 ? { x: mulBoxRow.predictLen, y: 0.6 } : { y: mulBoxRow.predictLen, x: 0.6 }
  1773. //单个的应该和多个的其中一端一样,且是离单个漫游点近的那端(也就是要走到箱子一端看不见其他箱子才行)
  1774. let dis0 = getBoxPos(mulBoxRow.left).distanceToSquared(singleBox.pano.position)
  1775. let dis1 = getBoxPos(mulBoxRow.right).distanceToSquared(singleBox.pano.position)
  1776. let near = dis0 < dis1 ? mulBoxRow.left : mulBoxRow.right
  1777. let p0 = getBoxPos(singleBox)
  1778. let dis = getBoxPos(near).distanceToSquared(p0)
  1779. rowInfo.score -= dis * 1000
  1780. let p1 = getBoxPos(mulBoxRow)
  1781. let vec1 = new THREE.Vector2(p1.x - singleBox.pano.position.x, p1.z - singleBox.pano.position.z).normalize() //看向中心的方向
  1782. let vec2 = new THREE.Vector2(singleBox.centerDir.x, singleBox.centerDir.z).normalize()
  1783. rowInfo.score += (vec1.dot(vec2) - 1) * 1000 //同一个方向是最好
  1784. }
  1785. }
  1786. function done(rowInfo) {
  1787. rowInfo && rowInfos.push(rowInfo)
  1788. rowInfos[name] = rowInfo
  1789. }
  1790. done(rowInfo)
  1791. return rowInfo
  1792. }
  1793. let matchGroups = []
  1794. let allRelations = []
  1795. let getK = info => {
  1796. let k
  1797. if (info.left) {
  1798. let vec = new THREE.Vector2(info.left.x - info.right.x, info.left.z - info.right.z)
  1799. k = Math.abs(vec.x / vec.y)
  1800. } else {
  1801. k = Math.abs(Math.max(info.size.x, 0.6) / Math.max(info.size.z, 0.6))
  1802. }
  1803. return k
  1804. }
  1805. let ignoreCountMatch = groups.filter(e => e.length > 1).length == 1 //是否不同数量box的row也能匹配
  1806. let minScore = boundConfirmed ? -2000 : -800
  1807. let match = searchType => {
  1808. if (searchType == 'second') ignoreCountMatch = true
  1809. for (let i = 0; i < groups.length - 1; i++) {
  1810. let rowBigBoxes_0 = getPanoBigRowBox(groups[i])
  1811. let pano0 = groups[i][0].pano
  1812. if (searchType == 'second') rowBigBoxes_0 = rowBigBoxes_0.filter(e => !matchGroups.some(u => u.includes(e)))
  1813. for (let j = i + 1; j < groups.length; j++) {
  1814. let rowBigBoxes_1 = getPanoBigRowBox(groups[j])
  1815. if (searchType == 'second') rowBigBoxes_1 = rowBigBoxes_1.filter(e => !matchGroups.some(u => u.includes(e)))
  1816. let pano1 = groups[j][0].pano
  1817. if (pano0.id == 54 && pano1.id == 56) {
  1818. console.log(2)
  1819. }
  1820. let resultPairs = []
  1821. let evaluateFun = (row0, row1) => {
  1822. return getRowMatchInfo(row0, row1, ignoreCountMatch)
  1823. }
  1824. searchPair(null /* bigBoxes_0[0] */, rowBigBoxes_0.slice(), rowBigBoxes_1.slice(), null, resultPairs, evaluateFun)
  1825. resultPairs = resultPairs.map(pairs => {
  1826. let infos = pairs.map(pair => (pair.some(e => e.sid == 'void') ? null : getRowMatchInfo(pair[0], pair[1], ignoreCountMatch)))
  1827. //infos.sort((a,b)=>{return a.score-b.score});
  1828. let score = infos.reduce((s, e) => {
  1829. return s + (e && e.score > minScore ? e.score : minScore / 2) //只考虑组成功的分数
  1830. }, 0)
  1831. return {
  1832. pairs,
  1833. infos,
  1834. score,
  1835. name: pairs.map(pair => pair.map(item => item.sid).join(' & ')),
  1836. }
  1837. })
  1838. resultPairs.sort((a, b) => b.score - a.score)
  1839. /* if (resultPairs[0].name[0].includes('pano8') && resultPairs[0].name[0].includes('pano0')) {
  1840. console.log(111)
  1841. } */
  1842. resultPairs[0] &&
  1843. resultPairs[0].pairs.forEach((pair, i) => {
  1844. let info = resultPairs[0].infos[i]
  1845. if (info && info.score > minScore) {
  1846. allRelations.push(info)
  1847. let items = pair.filter(e => e.sid != 'void')
  1848. common.pushToGroupAuto(items, matchGroups, null, atGroup => {
  1849. //需要朝向一致才行
  1850. if (!info.k) return true //(box识别的宽高识别不准所以不需要)
  1851. let onePair = atGroup.relationships[0]
  1852. let name = onePair[0].sid + '&' + onePair[1].sid
  1853. if (!rowInfos[name].k) return true //不过不应该有这种情况,否则匹配不到一起才对
  1854. if ((rowInfos[name].k < 1 && info.k < 1) || (rowInfos[name].k > 1 && info.k > 1)) {
  1855. return true
  1856. } else {
  1857. console.log('k不一致无法匹配', info, atGroup)
  1858. }
  1859. })
  1860. //根据目前的规则应该是有端点的和有端点的匹配,box和box匹配
  1861. }
  1862. })
  1863. //console.log(resultPairs[0])
  1864. }
  1865. }
  1866. }
  1867. match()
  1868. ignoreCountMatch || match('second') //再次将剩余的匹配一下,这次允许个数不同的row匹配
  1869. console.log('matchGroups', matchGroups)
  1870. //识别出来的多组,可能有重复的,因为box个数不同所以才没到一组
  1871. //整理一下,每个组整理出一个info,同时重新检查一下,挑去每组中和其他成员非常不同的
  1872. let groupInfo = []
  1873. let getGroupInfo = group => {
  1874. let left = new THREE.Vector3(),
  1875. right = new THREE.Vector3(),
  1876. pointsLen = 0
  1877. let bigBoxes = []
  1878. let info = {}
  1879. group.relationships.forEach(pair => {
  1880. let name = pair[0].sid + '&' + pair[1].sid
  1881. let matchInfo = rowInfos[name] //this.matchScoreMap["rowBigBox"][name] || this.matchScoreMap["cabinet"][name];
  1882. if (matchInfo.posLeft) {
  1883. left.add(matchInfo.posLeft), right.add(matchInfo.posRight), pointsLen++
  1884. } else {
  1885. bigBoxes.push(matchInfo)
  1886. preDealBox(matchInfo)
  1887. getBoxSize(matchInfo)
  1888. }
  1889. })
  1890. let index = groupInfo.length
  1891. if (pointsLen > 0) {
  1892. left.multiplyScalar(1 / pointsLen)
  1893. right.multiplyScalar(1 / pointsLen)
  1894. //addLabel(left, 'Left' + index, { bgcolor: '#F00', a: 0.2 })
  1895. //addLabel(right, 'Right' + index, { bgcolor: '#F00', a: 0.2 })
  1896. let center = new THREE.Vector3().addVectors(left, right).multiplyScalar(0.5)
  1897. //addLabel(center, 'center' + index, { bgcolor: '#F00', a: 0.3 })
  1898. ;(info.left = left), (info.right = right), (info.center = center)
  1899. info.pointsLen = pointsLen
  1900. }
  1901. if (bigBoxes.length > 0) {
  1902. let getAve = bigBoxes => {
  1903. let center1 = new THREE.Vector3(),
  1904. size = new THREE.Vector3()
  1905. bigBoxes.forEach(box => {
  1906. let center0 = getBoxPos(box)
  1907. center1.add(center0)
  1908. size.add(box.size)
  1909. })
  1910. if (pointsLen > 0) {
  1911. let size0 = new THREE.Vector3(Math.abs(left.x - right.x), size.y, Math.abs(left.z - right.z))
  1912. size.add(size0.multiplyScalar(pointsLen)).multiplyScalar(1 / (pointsLen + bigBoxes.length))
  1913. center1.add(info.center.clone().multiplyScalar(pointsLen)).multiplyScalar(1 / (pointsLen + bigBoxes.length))
  1914. } else {
  1915. size.multiplyScalar(1 / bigBoxes.length)
  1916. center1.multiplyScalar(1 / bigBoxes.length)
  1917. }
  1918. return { center1, size }
  1919. }
  1920. let getScores = (center, size) => {
  1921. //获得相对于center,size的差别分数
  1922. bigBoxes.forEach(box => {
  1923. box.sc = -box.center.distanceToSquared(center1) - size.distanceToSquared(box.size) * 0.5
  1924. })
  1925. }
  1926. let { center1, size } = getAve(bigBoxes)
  1927. //console.log(center1, size)
  1928. getScores(center1, size)
  1929. bigBoxes.sort((a, b) => b.sc - a.sc)
  1930. let midItem = bigBoxes[Math.floor(bigBoxes.length / 2)] //中位数
  1931. getScores(midItem.center, midItem.size)
  1932. const minScore = -8
  1933. let removes = bigBoxes.filter(e => {
  1934. return e.sc < minScore
  1935. })
  1936. if (removes.length) {
  1937. let { newGroups } = common.disconnectGroup(
  1938. removes.map(e => [e.box0, e.box1]),
  1939. matchGroups
  1940. )
  1941. console.log('去除错误数据', removes)
  1942. if (newGroups.length > 1) {
  1943. //分裂成多组了,重新计算
  1944. newGroups.forEach(e => {
  1945. getGroupInfo(e)
  1946. })
  1947. return
  1948. }
  1949. bigBoxes = bigBoxes.filter(e => {
  1950. return e.sc >= minScore
  1951. })
  1952. }
  1953. if (bigBoxes.length) {
  1954. let o = getAve(bigBoxes) //again
  1955. ;(info.center = o.center1), (info.size = o.size)
  1956. }
  1957. }
  1958. info.k = getK(info)
  1959. info.bigBoxes = bigBoxes
  1960. info.group = group
  1961. groupInfo.push(info)
  1962. }
  1963. matchGroups.slice(0).forEach(group => {
  1964. getGroupInfo(group)
  1965. })
  1966. let getLength = c => {
  1967. //获取bigbox长度
  1968. return c.size ? (c.k > 1 ? c.size.x : c.size.z) : c.k > 1 ? c.right.x - c.left.x : c.right.z - c.left.z + 0.6
  1969. }
  1970. let getLeft = (group, k) => {
  1971. let dirAxis = (k || group.k) > 1 ? 'x' : 'z'
  1972. return group.left ? group.left[dirAxis] - 0.3 : group.center[dirAxis] - group.size[dirAxis] / 2 //left和right加减半个宽度
  1973. }
  1974. let getRight = (group, k) => {
  1975. let dirAxis = (k || group.k) > 1 ? 'x' : 'z'
  1976. return group.right ? group.right[dirAxis] + 0.3 : group.center[dirAxis] + group.size[dirAxis] / 2
  1977. }
  1978. //识别是否group之间有一样的, 去重
  1979. {
  1980. let realGroups = []
  1981. let getAveWidth = (infos, len) => {
  1982. //获取这些infos最合适的箱子平均宽度和个数
  1983. let boxCounts = []
  1984. infos.forEach(e => {
  1985. boxCounts.push(...e.group.map(bigBox => bigBox.boxes.length))
  1986. })
  1987. boxCounts.sort((a, b) => a - b)
  1988. let midCounts = []
  1989. let r0 = 0.3,
  1990. r1 = 0.7 //取中间这部分的算最适合的个数,结果不一定是中位数
  1991. boxCounts.slice(Math.floor(boxCounts.length * r0), Math.floor(boxCounts.length * r1) + 1).forEach(c => {
  1992. if (!midCounts.includes(c)) midCounts.push(c)
  1993. })
  1994. let { min, max } = standards.cabinet.widthNormal
  1995. let standardW = (min + max) / 2
  1996. let aveWs = midCounts.map(e => {
  1997. return { aveW: len / e, count: e }
  1998. })
  1999. aveWs.sort((a, b) => Math.abs(a.aveW - standardW) - Math.abs(b.aveW - standardW))
  2000. let aveW = aveWs[0].aveW
  2001. let count = aveWs[0].count
  2002. if (aveW > max || aveW < min) {
  2003. let w = THREE.MathUtils.clamp(aveW, min, max)
  2004. //console.warn(`box aveW宽度不太对,从${aveW}修改到${w}`)
  2005. aveW = w
  2006. }
  2007. return { aveW, count }
  2008. }
  2009. let getBox2 = (center, len, thick, k) => {
  2010. let box2 = new THREE.Box2()
  2011. box2.expandByPoint(new THREE.Vector2(center.x, center.z))
  2012. let sizeVec = k > 1 ? new THREE.Vector2(len / 2, thick / 2) : new THREE.Vector2(thick / 2, len / 2)
  2013. box2.expandByVector(sizeVec)
  2014. return box2
  2015. }
  2016. const standardW = 0.6 //两排之间最小距离
  2017. for (let m = 0; m < groupInfo.length - 1; m++) {
  2018. let group0 = groupInfo[m]
  2019. for (let n = m + 1; n < groupInfo.length; n++) {
  2020. let group1 = groupInfo[n]
  2021. if (group1.bigBoxes[0]?.name == 'pano4-row-4&pano6-row-5,1' && group0.bigBoxes[0]?.name == 'pano4-row-2,5&pano6-row-3') {
  2022. console.log(4)
  2023. }
  2024. /* if (group0.k == 4.242560016595383 || group1.k == 0.8571428571428572) {
  2025. console.log(2)
  2026. } */
  2027. const maxR = 2.3
  2028. if (((group0.k > 1 && group1.k < 1) || (group0.k < 1 && group1.k > 1)) && getLength(group0) > 1.5 && getLength(group1) > 1.5) continue //如果是方块状的无视k
  2029. //间距
  2030. let spaceAxis = (group0.k + group1.k) / 2 > 1 ? 'z' : 'x'
  2031. let spaceDis = Math.abs(group0.center[spaceAxis] - group1.center[spaceAxis])
  2032. if (spaceDis > standardW * 1.5) continue
  2033. let o0 = getAveWidth([group0], getLength(group0)) //因为有可能长度和箱子个数不匹配,所以需要得到限制后的宽度再比较
  2034. let o1 = getAveWidth([group1], getLength(group1))
  2035. let len0 = (group0.predictLen = o0.aveW * o0.count)
  2036. let len1 = (group1.predictLen = o1.aveW * o1.count)
  2037. const minR = 0.5 //不可限制太死,因为有的框个数识别少了,导致len短。但可通过重叠面积来判断
  2038. // if( len0 / len1 < minR || len0 / len1 > 1/minR) continue
  2039. let area0 = (group0.area = len0 * o0.aveW)
  2040. let area1 = (group1.area = len1 * o1.aveW)
  2041. let getBoxMixArea = (expandRatio1, expandRatio2) => {
  2042. let box0 = getBox2(group0.center, len0 + expandRatio1, o0.aveW + expandRatio2, group0.k)
  2043. let box1 = getBox2(group1.center, len1 + expandRatio1, o1.aveW + expandRatio2, group1.k)
  2044. let mixBox = getMixBox(box0, box1) //重叠部分
  2045. let s = mixBox.getSize(new THREE.Vector2())
  2046. return { box0, box1, areaMix: Math.max(0, s.x) * Math.max(0, s.y) } //可能是0
  2047. }
  2048. let areaMixExpand = getBoxMixArea(0.1, 0.3).areaMix
  2049. if (areaMixExpand / area0 < 0.65 && areaMixExpand / area1 < 0.65) continue //包含的可以通过
  2050. /*let areaMix = getBoxMixArea(0, 0).areaMix //实际重合面积
  2051. group0.contains = group0.contains || []
  2052. group1.contains = group1.contains || []
  2053. group0.contains.push({ group: group1, selfPercent: areaMix / area0, percent2: areaMix / area1, areaMix })
  2054. group1.contains.push({ group: group0, selfPercent: areaMix / area1, percent2: areaMix / area0, areaMix })
  2055. */
  2056. //console.log('两个合并', group0, group1)
  2057. common.pushToGroupAuto([group0, group1], realGroups)
  2058. //包含的直接合并吧 - - ,这样会使结果偏移,不过没办法了,多个重叠面积太难算了
  2059. }
  2060. }
  2061. //但没合并前样本数量少,包含关系可能有错 - -
  2062. /*for(let m=0; m<groupInfo.length;m++){
  2063. let group = groupInfo[m]
  2064. let contains = group.contains.filter(e=> e.percent2 > 0.8) //所有包含的
  2065. contains.reduce
  2066. } */
  2067. groupInfo.forEach(info => {
  2068. //加入单个的
  2069. if (!realGroups.some(groups => groups.includes(info))) {
  2070. realGroups.push([info])
  2071. }
  2072. })
  2073. console.log('realGroups', realGroups)
  2074. //get boxes
  2075. realGroups.forEach((infos, i) => {
  2076. const sampleCount = infos.reduce((w, c) => {
  2077. return (w += c.pointsLen || c.bigBoxes.length)
  2078. }, 0)
  2079. let k
  2080. /* {
  2081. //const k = infos.reduce((w, c) => (w += c.k), 0) / infos.length
  2082. let ks = infos.map(e => e.k)
  2083. ks.sort((a, b) => a - b)
  2084. let min = ks[0],
  2085. max = ks[ks.length - 1]
  2086. if (min < 1 && max > 1) {
  2087. //比较最小和最大,选取更极端的那个
  2088. let min_ = 1 / min
  2089. if (min_ < max) k = max
  2090. else k = min
  2091. } else k = (min + max) / 2
  2092. } */
  2093. {
  2094. //看>1的和<1的平均数哪个多用哪个
  2095. let ks = { '<1': { count: 0, sum: 0 }, '>1': { count: 0, sum: 0 } }
  2096. infos.forEach(e => {
  2097. if (e.k < 1) {
  2098. ks['<1'].count++, (ks['<1'].sum += 1 / e.k)
  2099. } else {
  2100. ks['>1'].count++, (ks['>1'].sum += e.k)
  2101. }
  2102. })
  2103. ks['<1'].count && (ks['<1'].ave = ks['<1'].sum / ks['<1'].count)
  2104. ks['>1'].count && (ks['>1'].ave = ks['>1'].sum / ks['>1'].count)
  2105. if (ks['<1'].ave > ks['>1'].ave) {
  2106. k = 1 / ks['<1'].ave
  2107. } else {
  2108. k = ks['>1'].ave
  2109. }
  2110. }
  2111. let centerPos = infos
  2112. .reduce((w, c) => {
  2113. return w.add(c.center.clone().multiplyScalar(c.pointsLen || c.bigBoxes.length))
  2114. }, new THREE.Vector3())
  2115. .multiplyScalar(1 / sampleCount) //预得中心点
  2116. //获取左右端点(需要排除可能的误差,所以采用最靠近端点的三个点。但无法排除前三个点中万一含有包含box的、或者误差大的端点)
  2117. let lefts = infos
  2118. .map(e => getLeft(e, k))
  2119. .sort((a, b) => a - b)
  2120. .filter(a => a < centerPos[k > 1 ? 'x' : 'z'])
  2121. .slice(0, 3)
  2122. let rights = infos
  2123. .map(e => getRight(e, k))
  2124. .sort((a, b) => b - a)
  2125. .filter(a => a > centerPos[k > 1 ? 'x' : 'z'])
  2126. .slice(0, 3)
  2127. let left = 0,
  2128. right = 0
  2129. let c0 = ((lefts.length + 1) * lefts.length) / 2
  2130. lefts.forEach((e, i) => {
  2131. //越靠近最外侧权重越高。
  2132. left += e * ((lefts.length - i) / c0)
  2133. })
  2134. c0 = ((rights.length + 1) * rights.length) / 2
  2135. rights.forEach((e, i) => {
  2136. right += e * ((rights.length - i) / c0)
  2137. })
  2138. centerPos[k > 1 ? 'x' : 'z'] = (left + right) / 2
  2139. let len = right - left //加一点值是因为之前计算长度,用的是最外box的中心点,会少box一半宽度
  2140. let infos2 = infos.filter(e => {
  2141. return !e.predictLen || e.predictLen / len > 0.7
  2142. })
  2143. if (infos2.length == 0) {
  2144. infos2 = infos.sort((a, b) => b.predictLen - a.predictLen).slice(0, 1)
  2145. }
  2146. let { aveW, count } = getAveWidth(infos2, len)
  2147. //长宽比中心点的误差更大,尤其是box类型的、或样本少的
  2148. //获取高度
  2149. let heights = []
  2150. {
  2151. let pairs = [],
  2152. heightss
  2153. /* infos.forEach(e => {
  2154. pairs.push(...e.group.relationships.filter(pair => pair[0].boxes.length == count && pair[1].boxes.length == count))
  2155. })
  2156. if (pairs.length) {
  2157. heightss = pairs.map(pair => {
  2158. let boxes = pair.map(e => {
  2159. return e.boxes.slice()
  2160. })
  2161. let match = rowInfos[pair[0].sid + '&' + pair[1].sid]
  2162. let ifReverse = match.reversed
  2163. if (match.reversed == void 0 && pair[0].boxes.length > 1 && pair[1].boxes.length > 1) {
  2164. let { reversed } = getReverseInfo(pair[0], pair[1])
  2165. ifReverse = reversed
  2166. }
  2167. if (ifReverse) {
  2168. boxes[1].reverse()
  2169. }
  2170. let heights1 = []
  2171. let topPoss = []
  2172. for (let i = 0; i < count; i++) {
  2173. let match1 = getMatchScore(boxes[0][i], boxes[1][i], { onlyGet: true })
  2174. let topPos = match1 && match1.topPos
  2175. if (!topPos) {
  2176. topPos = getBoxTop({ box0: boxes[0][i], box1: boxes[1][i] })
  2177. }
  2178. heights1.push(topPos.y - groundY)
  2179. if (topPos.y - groundY < 0) {
  2180. console.log('?')
  2181. }
  2182. topPoss.push(topPos)
  2183. }
  2184. if ((k < 1 && topPoss[0].z > topPoss[count - 1].z) || (k > 1 && topPoss[0].x > topPoss[count - 1].x)) {
  2185. heights1.reverse()
  2186. }
  2187. return heights1
  2188. })
  2189. } else { */
  2190. let bigBoxes = []
  2191. infos.forEach(e => {
  2192. bigBoxes.push(...e.group.filter(e => !bigBoxes.includes(e) && e.boxes.length == count))
  2193. })
  2194. heightss = bigBoxes.map(bigBox => {
  2195. let topPoss = bigBox.boxes.map(box => {
  2196. let a = { box0: box }
  2197. getBoxTop(a)
  2198. return a.topPos
  2199. })
  2200. if ((k < 1 && topPoss[0].z > topPoss[count - 1].z) || (k > 1 && topPoss[0].x > topPoss[count - 1].x)) {
  2201. topPoss.reverse()
  2202. }
  2203. let heights1 = topPoss.map(topPos => topPos.y - groundY)
  2204. return heights1
  2205. })
  2206. //}
  2207. heightss.forEach(arr => {
  2208. for (let i = 0; i < count; i++) {
  2209. heights[i] = (heights[i] || 0) + arr[i]
  2210. }
  2211. })
  2212. heights = heights.map(e => {
  2213. let h = e / heightss.length
  2214. return h
  2215. })
  2216. //console.log('heightss',heightss, pairs, heights)
  2217. }
  2218. //拆分成小box
  2219. let size = new THREE.Vector3(aveW, 2, aveW)
  2220. let c = 0
  2221. infos.rowboxs = []
  2222. while (c < count) {
  2223. let center
  2224. if (k > 1) {
  2225. let startX = centerPos.x - ((count - 1) / 2) * aveW
  2226. center = new THREE.Vector3(startX + c * aveW, centerPos.y, centerPos.z)
  2227. } else {
  2228. let startZ = centerPos.z - ((count - 1) / 2) * aveW
  2229. center = new THREE.Vector3(centerPos.x, centerPos.y, startZ + c * aveW)
  2230. }
  2231. let size1 = heights[c] ? size.clone().setY(heights[c]) : size //如1*3的是得不到height的
  2232. let box = new Box({ name: 'row' + i + '-' + c, center, size: size1, boxType: 'cabinet', infos })
  2233. c++
  2234. infos.rowboxs.push(box)
  2235. }
  2236. })
  2237. return realGroups.length > 0
  2238. }
  2239. }
  2240. let removeContain = arr => {
  2241. //去除嵌套
  2242. let len = arr.length
  2243. if (len < 2) return
  2244. for (let i = 0; i < len - 1; i++) {
  2245. let box0 = arr[i]
  2246. getBoxBase(box0)
  2247. box0.contains = box0.contains || []
  2248. for (let j = i + 1; j < len; j++) {
  2249. let box1 = arr[j]
  2250. if (box0.sid == 'pano2-1' && box1.sid == 'pano2-7') {
  2251. console.log(6)
  2252. }
  2253. getBoxBase(box1)
  2254. box1.contains = box1.contains || []
  2255. let d3 = Math.abs(box1.bbox2CenterX - box0.bbox2CenterX) //限制d3是因为在相差180度两端可能也符合
  2256. //d4 = Math.abs(box1.bbox2[3] - box0.bbox2[3])
  2257. if (d3 > 0.4 /* || d4 > 0.01 */) continue
  2258. let d0 = getBbox2Diff(box1.bbox2[0], box0.bbox2[0]),
  2259. d1 = getBbox2Diff(box0.bbox2[2], box1.bbox2[2]),
  2260. w0 = getBbox2Diff(box0.bbox2[2], box0.bbox2[0]),
  2261. w1 = getBbox2Diff(box1.bbox2[2], box1.bbox2[0])
  2262. let min = Math.min(0.005, Math.min(w0, w1) * 0.2) //如果本身w0,w1宽度就小,差距更要小
  2263. if ((d1 >= 0 && Math.abs(d0) < min) || (d0 >= 0 && Math.abs(d1) < min) || (d1 >= 0 && d0 >= 0)) {
  2264. box0.contains.push(box1)
  2265. } else if ((d0 <= 0 && Math.abs(d1) < min) || (d1 <= 0 && Math.abs(d0) < min) || (d1 <= 0 && d0 <= 0)) {
  2266. box1.contains.push(box0)
  2267. }
  2268. }
  2269. }
  2270. let getWidthScore = (box, type) => {
  2271. const addDis = 0.1 //因为用的是btm的pos,比中心点近了一些,所以加上一段距离
  2272. let o = getBoxPoseByPos(box, getBoxPos(box), addDis)
  2273. let boxPjW = o.projectWidth
  2274. let standardPjW = (o.maxProjectWidth + o.minProjectWidth) / 2
  2275. let s = type == 'out' ? boxPjW - standardPjW : standardPjW - boxPjW
  2276. return -Math.pow(s, 2) * 10
  2277. }
  2278. let minChildCount = arr[0].boxType == 'battery' ? 1 : 2
  2279. arr.slice().forEach(box => {
  2280. if (box.contains.length >= minChildCount) {
  2281. //假设不存在第二层嵌套, 假设每个只能被一个嵌套
  2282. //决定留大还是留小
  2283. //先只去掉包含两个以上的,且角度范围一致
  2284. //尽量保留内层,除非内层太小
  2285. let { leftX, rightX } = getLeftRight(box.contains)
  2286. if (box.contains.length > 1 && (Math.abs(getBbox2Diff(box.bbox2[0], leftX)) > 0.005 || Math.abs(getBbox2Diff(box.bbox2[2], rightX)) > 0.005)) return //范围不一致
  2287. let remainChild = true
  2288. if (box.contains.length == 1) {
  2289. //cdi6xzNiNdS 电池包含单个 感觉一般都是留大
  2290. remainChild = false
  2291. } else {
  2292. let outScore = getWidthScore(box, 'out')
  2293. let childrenScores = box.contains.map(e => getWidthScore(e, 'in'))
  2294. let childAve = childrenScores.reduce((w, c) => w + c, 0) / childrenScores.length
  2295. if (childAve < -4) {
  2296. //let outScore = getWidthScore(box, 'out')
  2297. remainChild = childAve > outScore
  2298. }
  2299. }
  2300. if (!remainChild) {
  2301. box.contains.forEach(e => {
  2302. ;(e.state = '因被嵌套被删除'), (e.containBy = box)
  2303. arr.splice(arr.indexOf(e), 1)
  2304. console.log('因被嵌套被删除', ...box.contains)
  2305. })
  2306. } else {
  2307. box.state = '因嵌套其他被删除'
  2308. console.log('因嵌套其他被删除', box)
  2309. arr.splice(arr.indexOf(box), 1)
  2310. }
  2311. }
  2312. })
  2313. }
  2314. let waitFindRest = []
  2315. let Search = type => {
  2316. console.error('开始search', type)
  2317. let matchScoreMap = (this.matchScoreMap[type] = {})
  2318. let datas = {}
  2319. let panoIds = []
  2320. for (let id in this.datas) {
  2321. if (!this.datas[id]) continue
  2322. datas[id] = this.datas[id].shapes.filter(e => isType(e.category, type))
  2323. datas[id].length && panoIds.push(id)
  2324. }
  2325. for (let id in this.datas) {
  2326. //对data预处理
  2327. //(之后如果还出现不同类型重叠在一起的,需要先识别摘除下。 )4GqaqNdyjGf
  2328. if (!this.datas[id]) continue
  2329. removeContain(datas[id]) //去除线框中的嵌套,主要是一个嵌套两个的。案例:KK-1Zjm9Rbl47
  2330. if (datas[id].length) {
  2331. //融合。很多box被一分为二了,基本都是在全景图左右边界处。
  2332. let bigBoxes = getPanoBigRowBox(datas[id], { reason: 'mix' })
  2333. bigBoxes.forEach(bigBox => {
  2334. if (bigBox.boxes.length > 1) {
  2335. bigBox.boxes.forEach(box => {
  2336. ;(box.state = '被删除'), (box.mixTo = bigBox)
  2337. let i = datas[id].indexOf(box)
  2338. datas[id].splice(i, 1)
  2339. if (version == 'vision') {
  2340. i = this.datasMixed[id].shapes.findIndex(e => e.sid == box.sid)
  2341. this.datasMixed[id].shapes.splice(i, 1)
  2342. }
  2343. })
  2344. //console.log('因融合而删除', bigBox.boxes)
  2345. datas[id].push(bigBox)
  2346. if (version == 'vision') {
  2347. this.datasMixed[id].shapes.push(bigBox)
  2348. }
  2349. let shapes = this.datas[id].shapes
  2350. bigBox.index = shapes.length > 1 ? shapes[shapes.length - 2].index + 1 : 0
  2351. {
  2352. let a = bigBox.sid.split('mix-')
  2353. bigBox.sid = a[0] + bigBox.index + '(mix' + a[1] + ')' //"pano20-mix-1,2"
  2354. }
  2355. }
  2356. })
  2357. }
  2358. }
  2359. if (panoIds.length == 0) {
  2360. if (standards[type].tinyXZ) {
  2361. //fire 调试:nZrBdvRaDuC
  2362. this.expandModelBound()
  2363. }
  2364. return
  2365. }
  2366. panoIds.sort((a, b) => {
  2367. return datas[b].length - datas[a].length
  2368. })
  2369. let groups = panoIds.map(e => datas[e])
  2370. console.log('按box个数排序:', groups.slice())
  2371. let group0 = groups[0],
  2372. len0 = group0.length
  2373. if (groups.length == 1) {
  2374. //只有一个全景里有数据
  2375. if (standards[type].tinyXZ) {
  2376. //fire. 无法match以获取groundY, 就取消。 调试: eGhyf5QdVHA
  2377. this.expandModelBound(type)
  2378. }
  2379. group0.forEach(e => createSinglePano(e))
  2380. return combines(type)
  2381. }
  2382. let finish = groups => {
  2383. waitFindRest.push({ type, args: [groups] }) //等待最后检查遗漏
  2384. if (standards[type].tinyXZ) {
  2385. //fire 调试:nZrBdvRaDuC
  2386. this.confirmGroundY(type)
  2387. }
  2388. if (standards[type].tiny) {
  2389. //monitor 调试:S9yepREK8Jl
  2390. this.expandModelBound2(type)
  2391. }
  2392. }
  2393. if (len0 == 1) {
  2394. //最多的也只有一个box。此情况大部分是空调
  2395. panoIds.forEach(e => getBoxBase(datas[e][0]))
  2396. let maxAngle
  2397. //找出centerDir夹角最大的两个pano
  2398. for (let i = 0; i < panoIds.length; i++) {
  2399. let box0 = datas[panoIds[i]][0]
  2400. for (let j = i + 1; j < panoIds.length; j++) {
  2401. let box1 = datas[panoIds[j]][0]
  2402. getMatchScore(box0, box1, { isSingle: true })
  2403. }
  2404. }
  2405. let list = Object.keys(matchScoreMap)
  2406. list.sort((a, b) => {
  2407. return matchScoreMap[b].score - matchScoreMap[a].score
  2408. })
  2409. let match = matchScoreMap[list[0]]
  2410. preDealBox(match)
  2411. if (match.score > -100) {
  2412. getBoxSize(match)
  2413. if (match.score > 0 && match.sizeAdjust < 0.1) {
  2414. new Box(matchScoreMap[list[0]])
  2415. //waitFindRest.push({ type, args: [groups] }) //等待最后检查遗漏
  2416. finish(groups)
  2417. return
  2418. }
  2419. }
  2420. //根据分数重排序,前两个已匹配的pano放在第一第二(reMatchLowScores会跳过),获得groups2
  2421. let panoIds2 = []
  2422. list.forEach(e => {
  2423. let info = matchScoreMap[e]
  2424. if (!panoIds2.includes(info.box0.pano.id)) panoIds2.push(info.box0.pano.id)
  2425. if (!panoIds2.includes(info.box1.pano.id)) panoIds2.push(info.box1.pano.id)
  2426. })
  2427. let groups2 = panoIds2.map(e => datas[e])
  2428. //继续match
  2429. reMatchLowScores([match], groups2)
  2430. finish(groups2)
  2431. return
  2432. }
  2433. {
  2434. //重新根据距离排序,挑选离所有box距离最近的两个pano (远的可能看不到box,或者得到的线框计算的位置不准。不过其实太近也不准-,-)
  2435. let counts = {}
  2436. groups.forEach(e => {
  2437. e.forEach(a => getBoxBase(a))
  2438. counts[e.length] || (counts[e.length] = [])
  2439. counts[e.length].push(e)
  2440. })
  2441. groups = []
  2442. let atWall = standards[type].atWall
  2443. let nums = Object.keys(counts)
  2444. let bestDisSquared = 2
  2445. nums.reverse()
  2446. nums.forEach(count => {
  2447. let groups_ = counts[count]
  2448. if (groups_.length > 1) {
  2449. groups_.forEach(e => {
  2450. e.disSc = e.reduce((w, c) => {
  2451. let pos = getBoxPos(c)
  2452. //let s = atWall ? Math.pow(Math.abs(c.centerDir.y), 3)*100 : 0 //在墙上的话尽量平视
  2453. //console.log(c.sid,s)
  2454. return w + Math.abs(c.pano.position.distanceToSquared(pos) - bestDisSquared) //+ s
  2455. }, 0)
  2456. })
  2457. groups_.sort((a, b) => a.disSc - b.disSc)
  2458. }
  2459. groups.push(...groups_)
  2460. })
  2461. console.log('按距离和个数排序:', groups)
  2462. group0 = groups[0]
  2463. len0 = group0.length
  2464. }
  2465. if (type == 'cabinet') {
  2466. //转化为分组
  2467. if (searchByRow(groups, datas)) {
  2468. waitFindRest.push({ type, args: [groups, 0] }) //等待最后检查遗漏
  2469. return
  2470. }
  2471. }
  2472. //零散匹配。
  2473. let match2Group = (group0, group1, { fake }) => {
  2474. let len0 = group0.length,
  2475. len1 = group1.length
  2476. for (let i = 0; i < len0; i++) {
  2477. //复杂度:n的平方次
  2478. for (let j = 0; j < len1; j++) {
  2479. let box1 = group0[i]
  2480. let box2 = group1[j]
  2481. let result = getMatchScore(box1, box2)
  2482. }
  2483. }
  2484. //寻找最佳配对 n!种组合(是否要限制个数多的情况?) 超过8个就很恐怖
  2485. //仅先查找选中的两个pano配对
  2486. let resultPairs = []
  2487. let newGroup0 = group0.slice(0)
  2488. let newGroup1 = group1.slice(0)
  2489. /* while (newGroup1.length < newGroup0.length) {
  2490. newGroup1.push({ sid: 'void' }) //为了使排列正确,补个空,使左右两边个数相等,过后和void匹配的不会计算box
  2491. } */
  2492. let evaluateFun = getMatchScore.bind(this)
  2493. searchPair(/* group0[0] */ null, newGroup0, newGroup1, null, resultPairs, evaluateFun)
  2494. /* console.log(
  2495. 'resultPairs',
  2496. resultPairs.map(pairs => pairs.map(pair => pair.map(item => item.sid).join(' & ')))
  2497. ) */
  2498. resultPairs = resultPairs.map(pairs => {
  2499. let infos = pairs.map(pair => matchScoreMap[pair[0].sid + '&' + pair[1].sid])
  2500. let score = infos.reduce((s, e) => {
  2501. return s + (e ? e.score : 0)
  2502. }, 0)
  2503. let o = {
  2504. infos,
  2505. score,
  2506. pairs,
  2507. name: pairs.map(pair => pair.map(item => item.sid).join(' & ')),
  2508. }
  2509. return o
  2510. })
  2511. //console.log('resultPairs', resultPairs.slice())
  2512. console.log(
  2513. 'resultPairs按分数高低',
  2514. resultPairs.sort((a, b) => b.score - a.score)
  2515. )
  2516. //console.log('compu',compu)
  2517. let minScore = boundConfirmed ? -2000 : -800
  2518. let noMatches = [] //和void匹配的,需要和其他pano的重新匹配
  2519. let mayHaventMatched = []
  2520. let lowScores = []
  2521. if (resultPairs[0]) {
  2522. resultPairs[0].infos.forEach((info, i) => {
  2523. if (!info) {
  2524. noMatches.push(resultPairs[0].pairs[i].find(e => e.sid != 'void'))
  2525. return //match with void
  2526. }
  2527. if (info.score < minScore || (standards[info.boxType].bottom && info.minAng < 5)) {
  2528. lowScores.push(info)
  2529. return
  2530. }
  2531. preDealBox(info)
  2532. getBoxSize(info)
  2533. if ((info.sizeAdjust && standards[info.boxType].tiny) || info.sizeAdjust > 0.2) {
  2534. //或者识别下悬挂的且线的角度较小
  2535. lowScores.push(info)
  2536. return
  2537. }
  2538. if (info.box0.category == typeNames.battery && info.size.x < 1 && info.size.z < 1) {
  2539. //宽度较小
  2540. let vec0 = new THREE.Vector3().subVectors(info.box0.pano.position, getBoxPos(info))
  2541. let vec1 = new THREE.Vector3().subVectors(info.box1.pano.position, getBoxPos(info))
  2542. /* let k0 = Math.abs(vec0.x / vec0.z), k1 = Math.abs(vec1.x / vec1.z), maxR = 6
  2543. if(info.name == '') */
  2544. if (vec0.x * vec1.x > 0 && vec0.z * vec1.z > 0 /* || k0/k1 > maxR || k0/k1 < 1/maxR */) {
  2545. //同一个象限 或 偏向一侧
  2546. lowScores.push(info)
  2547. return
  2548. }
  2549. }
  2550. info.fake = fake
  2551. let box = new Box(info)
  2552. })
  2553. }
  2554. if (noMatches.length) {
  2555. reMatchLowScores(
  2556. noMatches.map(e => {
  2557. return { box0: e }
  2558. }),
  2559. groups,
  2560. { fake }
  2561. )
  2562. }
  2563. reMatchLowScores(lowScores, groups, { fake })
  2564. }
  2565. {
  2566. for (let i = 0; i < groups.length - 1; i++) {
  2567. match2Group(groups[i], groups[i + 1], { fake: i > 0 })
  2568. if (!standards[type].tinyXZ /* && !browser.urlHasValue('many') */ || groups[i + 1].length < 2) {
  2569. break
  2570. }
  2571. }
  2572. }
  2573. finish(groups)
  2574. }
  2575. function blocked(box) {
  2576. //该box是否被实体box遮挡
  2577. //WcLVXvmV9AU:pano2-2 和 pano12-4 ; 5yhlMduTHL8:pano2-10
  2578. /* if (box.sid == 'pano6-7') {
  2579. console.log(1)
  2580. addLine(box.pano.position, box.centerBtmDir, 20)
  2581. } */
  2582. if (!standards[box.boxType].bottom) {
  2583. //当底部每个方向都有遮挡物时,其位置很可能不准。但若是部分遮住,还是有可能识别对的
  2584. if (!box.blocked) {
  2585. box.blocked = {
  2586. centerBtmDir: null,
  2587. leftBtmDir: null,
  2588. rightBtmDir: null,
  2589. }
  2590. }
  2591. for (let dir in box.blocked) {
  2592. if (!box.blocked[dir]) {
  2593. let block = boxesSolid.find(boxSolid => {
  2594. ray.set(box.pano.position, box[dir])
  2595. let o = ray.ray.intersectsBox(boxSolid.bound)
  2596. if (o) {
  2597. // 遮挡
  2598. return true
  2599. }
  2600. })
  2601. if (block) {
  2602. //若不存在,即都遮挡了,就算真的遮挡
  2603. box.blocked[dir] = block
  2604. } else {
  2605. box.blocked[dir] = false
  2606. return false //找到一个方向无遮挡则可返回
  2607. }
  2608. }
  2609. }
  2610. return true
  2611. //暂定,若某个方向已得到遮挡了,就不计算。但若没有,就再搜一遍(如果会重复搜之后再增加一个stamp啥的,比如记录下当前所有solidBoxes的name,如果改变了就重新搜下)
  2612. } else {
  2613. //若中心方向已经有同类型的box,很可能它就是自身(因为挂墙的预测位置很不准,所以需要这一步。越tiny的越能通过此来筛选)
  2614. let block = boxesSolid.find(boxSolid => {
  2615. if (boxSolid.boxType != box.boxType) return
  2616. ray.set(box.pano.position, box.centerDir)
  2617. let o = ray.ray.intersectsBox(boxSolid.bound)
  2618. if (o) {
  2619. // 遮挡
  2620. return true
  2621. }
  2622. })
  2623. if (block) {
  2624. box.blocked = block
  2625. return true
  2626. }
  2627. }
  2628. }
  2629. //调试 O540aEVF3b7 jQUQlER160 n4z0yd5tQaF WcLVXvmV9AU 8czlwsbSe5 NlUM8yGve9
  2630. function findRest(groups /* ,startIndex=2 */) {
  2631. //查找是否有遗漏。
  2632. //1 可能有距离较远的box不在头两个pano的附近导致被漏掉。(概率很小)
  2633. //2 被剩余的 (包括低分匹配中放弃的,这种需要的距离识别度高)
  2634. const tolerateWidth = { min: 0.1, max: 0.5 }
  2635. let boxes = [],
  2636. scores = new Map(),
  2637. bestDisSquared = 2
  2638. groups.forEach(g => {
  2639. boxes.push(...g)
  2640. })
  2641. boxes = boxes.filter(box => !used(box))
  2642. boxes.forEach(box => {
  2643. getBoxBase(box)
  2644. let p1 = new THREE.Vector2(box.pano.position.x, box.pano.position.z)
  2645. let p2 = new THREE.Vector2(box.btmPos.x, box.btmPos.z)
  2646. let dis = p1.distanceToSquared(p2)
  2647. let s1 = -Math.abs(dis - bestDisSquared) //将距离最佳的排前面,距离远的得到的位置不准确,也容易被遮
  2648. if (!box.pose) box.pose = getBoxPoseByPos(box, getBoxPos(box))
  2649. let s2 = getPoseScore([box.pose], box.boxType) + THREE.MathUtils.clamp(box.pose.projectWidth, box.pose.minProjectWidth, box.pose.maxProjectWidth) * 7 //projectWidth长的更安全
  2650. scores.set(box, { s1, s2, sum: s1 + s2 })
  2651. })
  2652. //console.log(boxes[0].boxType,scores)
  2653. boxes = boxes.sort((a, b) => {
  2654. return scores.get(b).sum - scores.get(a).sum
  2655. }) //FXcq5PI9QGv
  2656. //console.log(boxes)
  2657. boxes.forEach(box => {
  2658. if (box.sid == 'pano0-4') {
  2659. console.log(3)
  2660. }
  2661. if (!used(box) && !blocked(box)) {
  2662. //如果和现有的box的距离都很远,很可能是漏掉的
  2663. let near = boxesSolid.find(solidBox => {
  2664. if (solidBox.name == 'air-pano16-7&pano14-13') {
  2665. console.log(3)
  2666. }
  2667. if (solidBox.boxType != box.boxType && (solidBox.boxType == 'air-hanging' || box.boxType == 'air-hanging')) return //挂空调一般不会撞到地面上的
  2668. let p1 = getBoxPos(solidBox)
  2669. let p2 = getBoxPos(box)
  2670. let p1_ = new THREE.Vector2(p1.x, p1.z)
  2671. let p2_ = new THREE.Vector2(p2.x, p2.z)
  2672. let maxWidth = standards[box.boxType].widthNormal.max / 2
  2673. maxWidth = THREE.MathUtils.clamp(maxWidth, tolerateWidth.min, tolerateWidth.max) //因为场景精度存在较大误差,所以maxWidth不能过小,否则像灭火器摄像头都容易findRest多个
  2674. let dis = solidBox.bound.distanceToPoint(p2)
  2675. //let r0 = solidBox.boxType == 'air' ? 2 : solidBox.boxType == 'battery' ? 1.1 : 1 //空调最不容易扎堆放置,所以范围设置广一些
  2676. let r0 = standards[box.boxType].closeRatio
  2677. let r1 = math.linearClamp(box.pano.position.distanceTo(p2), 3, 20, 1, 5) //距离远的话识别、计算都会更不准确,给一定的容错. 远的尽量不findRest,即尽量>0
  2678. let ra = (solidBox.boxType == box.boxType ? 1 : 0.5) * r0 * r1 //数字越小限制越大
  2679. if (box.sid == 'pano48-5') {
  2680. console.log(1)
  2681. }
  2682. /* let a = maxWidth * maxWidth * ra - p1_.distanceToSquared(p2_)
  2683. let b = -dis * dis * 0.7
  2684. let c = a + b*/
  2685. let c = maxWidth * ra - dis * 1.3
  2686. if (c > 0) {
  2687. //太近 不创建
  2688. console.log(1)
  2689. }
  2690. return c > 0
  2691. })
  2692. if (!near) {
  2693. reMatchLowScores([{ box0: box, log: 'findRest' }], groups, { startIndex: 0 })
  2694. } else {
  2695. //console.log('find near', near.name, box.sid)
  2696. }
  2697. }
  2698. })
  2699. }
  2700. function used(box) {
  2701. //是否已经使用过
  2702. let has = e => {
  2703. return e.box0 == box || e.box1 == box
  2704. }
  2705. let traverse = e => {
  2706. return (
  2707. has(e) ||
  2708. (e.list && e.list.some(a => traverse(a))) ||
  2709. (e.mixedFrom && e.mixedFrom.some(a => traverse(a))) ||
  2710. (e.infos && e.infos.some(u => u.group.some(r => r.boxes.some(b => b == box))))
  2711. ) //row
  2712. }
  2713. return boxesSolid.some(e => traverse(e))
  2714. }
  2715. function reMatchLowScores(lowScores, groups, { startIndex = 2, fake } = {}) {
  2716. let matched = [],
  2717. tooLows = []
  2718. let minScore = boundConfirmed ? -2000 : -800
  2719. let isSameMatch = (match0, match1) => {
  2720. //是否对应同一个box实体(不一定准),通过两两box之间是否都match来判断
  2721. //如果是相同pano但不同的box肯定不是对应同一个box实体
  2722. let ifWrong = (box0, box1) => {
  2723. if (box0 == box1) return
  2724. if (box0.pano == box1.pano) return true
  2725. let match2 = getMatchScore(box0, box1, { isSingle: true, restMatch: true })
  2726. if (match2.score < minScore) return true
  2727. }
  2728. if (ifWrong(match0.box0, match1.box0) || ifWrong(match0.box1, match1.box1) || ifWrong(match0.box0, match1.box1) || ifWrong(match0.box1, match1.box0)) return
  2729. return true
  2730. }
  2731. if (lowScores.length) {
  2732. console.warn(lowScores[0].log || (lowScores[0].box1 ? '低分重新匹配' : '剩余匹配'), lowScores[0].box0.boxType, ...lowScores)
  2733. if (lowScores[0].box1) {
  2734. lowScores.sort((a, b) => {
  2735. //低分优先
  2736. return a.score - b.score
  2737. })
  2738. }
  2739. lowScores.forEach(info => {
  2740. //info中的box0和box1分别向后寻找其他的配对。选择分数高的配对。 但box0和box1可能是错误配对,会导致找到了替代的也可能遗漏。
  2741. /* if (info.name == 'pano0-3&pano2-3') {
  2742. console.log(1)
  2743. } */
  2744. let box01 = info.box0
  2745. let box02 = info.box1
  2746. let bigGroup = []
  2747. box02 && bigGroup.push(info)
  2748. let got
  2749. for (let cur = startIndex; cur < groups.length; cur++) {
  2750. let thirdGroup = groups[cur]
  2751. let scores0 = [],
  2752. scores1 = []
  2753. thirdGroup.forEach(box1 => {
  2754. //if (matched.includes(box1.sid)) return
  2755. if (used(box1)) return //会不会太严格?
  2756. if (box1.pano != box01.pano && box1 != box02) {
  2757. let r1 = getMatchScore(box01, box1, { isSingle: true, restMatch: true })
  2758. r1.score > minScore * 1.5 && scores0.push(r1)
  2759. }
  2760. if (box02 && box1.pano != box02.pano && box1 != box01) {
  2761. let r2 = getMatchScore(box02, box1, { isSingle: true, restMatch: true })
  2762. r2.score > minScore * 1.5 && scores1.push(r2)
  2763. }
  2764. })
  2765. scores0.sort((a, b) => {
  2766. return b.score - a.score
  2767. })
  2768. scores1.sort((a, b) => {
  2769. return b.score - a.score
  2770. })
  2771. scores0[0] && bigGroup.push(scores0[0])
  2772. scores1[0] && bigGroup.push(scores1[0])
  2773. }
  2774. bigGroup.sort((a, b) => {
  2775. return b.score - a.score
  2776. })
  2777. let goodList = bigGroup.slice(0, 10).map(e => {
  2778. if (!getBoxPos(e)) return e
  2779. preDealBox(e)
  2780. getBoxSize(e)
  2781. return e
  2782. })
  2783. let goodList2 = goodList
  2784. .sort((a, b) => {
  2785. return b.score - a.score
  2786. })
  2787. .slice(0, 3)
  2788. if (goodList2.length == 0) {
  2789. return fake || createSinglePano(box01, 0.6) //minScorePercent原因:剩余匹配时位置不太好的案例: AhMgXXjM15
  2790. }
  2791. if (goodList2[0].score > minScore * 0.65) {
  2792. goodList2 = goodList2.filter(e => e.score > minScore * 0.65)
  2793. } else {
  2794. /* goodList2 = [goodList2[0]] // 最高分已经过小
  2795. if (goodList2[0].score < -1500) { */
  2796. if (!box02) {
  2797. if (info.log == 'findRest' || getBoxPos(box01).distanceTo(box01.pano.position) < 2.5) {
  2798. //远距离不准,留到过后findRest
  2799. fake || createSinglePano(box01)
  2800. }
  2801. return
  2802. }
  2803. //console.warn('分数过低,是否有匹配错误?', goodList2[0])
  2804. return tooLows.push(goodList2[0])
  2805. //}
  2806. }
  2807. if (goodList2.length) {
  2808. //需要确认两两之间是配对的,也就是都对应同一个box
  2809. let subGroups = [],
  2810. boxes = []
  2811. for (let i = 0, len = goodList2.length; i < len; i++) {
  2812. //向后选择队友
  2813. let match0 = goodList2[i]
  2814. if (subGroups.some(e => e.includes(match0))) continue //被挑选了的没有选择权
  2815. let gr = [match0]
  2816. for (let j = i + 1; j < len; j++) {
  2817. let match1 = goodList2[j]
  2818. if (isSameMatch(match0, match1)) {
  2819. //可能不是同一个,所以需要检验
  2820. gr.push(match1)
  2821. }
  2822. }
  2823. //if(gr.length>1){
  2824. subGroups.push(gr)
  2825. //}
  2826. }
  2827. //console.log('lowScores subGroups', subGroups)
  2828. subGroups.forEach(pair => {
  2829. boxes.push(mixMatchBox(pair, lowScores[0].log, fake))
  2830. })
  2831. fake || combineBoxes(boxes) //很可能其实还是同一个,需要检验是否要融合
  2832. }
  2833. })
  2834. //改为之后 findRest, 因为两者都single的可能性低
  2835. /* let judge = box => {
  2836. if (!used(box)) {
  2837. matched.push(box)
  2838. createSinglePano(box)
  2839. }
  2840. }
  2841. tooLows.forEach(e => {
  2842. judge(e.box0)
  2843. judge(e.box1)
  2844. }) */
  2845. }
  2846. }
  2847. function mixMatchBox(list, log, fake) {
  2848. let center = new THREE.Vector3(),
  2849. size = new THREE.Vector3(),
  2850. name,
  2851. bound = new THREE.Box3()
  2852. list.forEach(e => {
  2853. let _bound = new THREE.Box3().setFromCenterAndSize(getBoxFinalPos(e), e.size)
  2854. bound.union(_bound)
  2855. })
  2856. //bound.getCenter(center) //这两种获得center的方法哪个准?
  2857. bound.getSize(size)
  2858. list.forEach(e => center.add(getBoxPos(e)))
  2859. center.multiplyScalar(1 / list.length)
  2860. let { xProp, yProp } = list.find(e => e.xProp) || {}
  2861. if (xProp && list.find(e => e.xProp && e.xProp != xProp)) {
  2862. //如果有不同的话
  2863. xProp = yProp = null
  2864. }
  2865. let prefix = log == 'findRest' ? 'rest:' : 'low:'
  2866. let object = {
  2867. name: prefix + list.map(e => e.name),
  2868. boxType: list[0].boxType,
  2869. center,
  2870. size,
  2871. list,
  2872. xProp,
  2873. yProp,
  2874. }
  2875. xProp || getBoxDirProp(object)
  2876. let o = restrictSize(size.x, size.y, size.z, object)
  2877. size.x = o.x
  2878. size.y = o.y
  2879. size.z = o.z
  2880. object.fake = fake
  2881. let box = new Box(object)
  2882. //console.log('mixMatchBox', box)
  2883. return box
  2884. }
  2885. function combineBoxes(boxes, typeCount) {
  2886. //调试 tY4ot33f8vT UWrshepp0G5的一高一低的电箱
  2887. //判断这些实体boxes是否需要合并 主要用于重复识别(重叠面积较大) 电池还可能是拼接
  2888. const group = []
  2889. if (boxes.length > 1) {
  2890. let boxType = boxes[0].boxType
  2891. let { min, max } = standards[boxType].widthNormal
  2892. for (let i = 0, len = boxes.length; i < len - 1; i++) {
  2893. let box0 = boxes[i]
  2894. if (box0.fake) continue
  2895. for (let j = i + 1; j < len; j++) {
  2896. let box1 = boxes[j]
  2897. if (box1.fake) continue
  2898. let bound = box0.bound.clone().union(box1.bound)
  2899. let size = bound.getSize(new THREE.Vector3())
  2900. let intersect = box0.bound.intersectsBox(box1.bound)
  2901. if (box0.boxType == 'electric') {
  2902. console.log(1)
  2903. }
  2904. let minX = min,
  2905. minZ = min,
  2906. maxX = max,
  2907. maxZ = max,
  2908. maxY = standards[boxType].height.max
  2909. if (box0.xProp && box1.xProp && box0.xProp == box1.xProp) {
  2910. maxX = standards[boxType][box0.xProp].max
  2911. maxZ = standards[boxType][box0.yProp].max
  2912. /* minX = standards[boxType][box0.xProp].min
  2913. minZ = standards[boxType][box0.yProp].min */
  2914. if (box0.boxType != box1.boxType) {
  2915. //air & airSmart
  2916. maxX = Math.max(maxX, standards[box1.boxType][box1.xProp].max)
  2917. maxZ = Math.max(maxZ, standards[box1.boxType][box1.yProp].max)
  2918. /* minX = Math.min(minX, standards[box1.boxType][box1.xProp].min)
  2919. minZ = Math.min(minZ, standards[box1.boxType][box1.yProp].min) */
  2920. }
  2921. }
  2922. maxX = Math.max(maxX, box0.size.x, box1.size.x) //必须大于各自的size,否则无法去除本身就oversize的box中包含的
  2923. maxZ = Math.max(maxZ, box0.size.z, box1.size.z)
  2924. maxY = Math.max(maxY, box0.size.y, box1.size.y)
  2925. let r = intersect ? 1.5 : 1.3 /* / standards[box1.boxType].closeRatio */ //如果是没有交集,限制更大些
  2926. //若需要更精确的结果,可以getMixBox算出重叠面积,重叠少,且各自都不太小,就不合并。但考虑到电池边界很模糊,合并了也无大碍。
  2927. if (box0.boxType == 'battery') {
  2928. r *= 1.3 //比较可能扎堆
  2929. }
  2930. let maxDiff = 0.4,
  2931. maxDiffX = maxDiff,
  2932. maxDiffZ = maxDiff,
  2933. rx = r,
  2934. rz = r
  2935. if (standards[box0.boxType].atWall == 1) {
  2936. //在墙面上不可能叠放,所以厚度限制可放宽
  2937. let s = 4
  2938. if (box0.yProp == 'width') {
  2939. maxDiffX *= s
  2940. rx *= s
  2941. } else if (box0.xProp == 'width') {
  2942. maxDiffZ *= s
  2943. rz *= s
  2944. }
  2945. }
  2946. //如果某个点位含有类似和这俩相近的box: A9rCPzp2UD9两个fire合并了。好难写,算了
  2947. /* if(box0.boxType){
  2948. this.datasMixed
  2949. rx = rz = 1.1
  2950. } */
  2951. if (size.x - maxX < maxDiffX && size.x < maxX * rx && size.z < maxZ * rz && size.z - maxZ < maxDiffZ && size.y < maxY * r && size.y - maxY < maxDiff) {
  2952. //总size不会太大
  2953. common.pushToGroupAuto([box0, box1], group)
  2954. }
  2955. }
  2956. }
  2957. if (group.length) {
  2958. //虽然如果三个以上可能会超出maxWidth。 不过3个的概率很低,且可以限制宽度
  2959. group.forEach(pair => {
  2960. let boxTypes = []
  2961. let bound = new THREE.Box3()
  2962. pair.forEach(e => {
  2963. bound.union(e.bound)
  2964. e.dispose()
  2965. if (typeCount > 1) {
  2966. //判断boxType: 寻找所使用的box总分最高的boxType
  2967. let a = boxTypes.find(a => a.boxType == e.boxType)
  2968. let score = 0
  2969. let add = box => {
  2970. box && (score += box.score)
  2971. }
  2972. e.traversePair(e => {
  2973. add(e.box0)
  2974. add(e.box1)
  2975. })
  2976. if (a) {
  2977. a.score += score
  2978. } else {
  2979. boxTypes.push({ score, boxType: e.boxType })
  2980. }
  2981. }
  2982. })
  2983. if (typeCount > 1) {
  2984. boxTypes.sort((a, b) => {
  2985. return b.score - a.score
  2986. })
  2987. boxType = boxTypes[0].boxType
  2988. }
  2989. let size = bound.getSize(new THREE.Vector3())
  2990. let center = bound.getCenter(new THREE.Vector3())
  2991. let { xProp, yProp } = pair.find(e => e.xProp) || {}
  2992. if (xProp && pair.find(e => e.xProp && e.xProp != xProp)) {
  2993. //如果有不同的话
  2994. xProp = yProp = null
  2995. }
  2996. let info = {
  2997. name: 'mix:' + pair.map(e => ' ' + e.name),
  2998. mixedFrom: pair,
  2999. boxType,
  3000. center,
  3001. size,
  3002. xProp,
  3003. yProp,
  3004. }
  3005. xProp || getBoxDirProp(info)
  3006. let o = restrictSize(size.x, size.y, size.z, info)
  3007. size.x = o.x
  3008. size.y = o.y
  3009. size.z = o.z
  3010. let box = new Box(info)
  3011. console.error('混合', boxType, pair, box)
  3012. })
  3013. }
  3014. }
  3015. }
  3016. function combines(types) {
  3017. //合并boxSolids . battery经常嵌套
  3018. if (!(types instanceof Array)) types = [types]
  3019. let boxes = boxesSolid.filter(e => types.includes(e.boxType))
  3020. combineBoxes(boxes, types.length)
  3021. }
  3022. let createSinglePano = (box, minScorePercent = 1) => {
  3023. //仅用一个pano中的data来创建。 悬挂于墙上的准确性依赖于墙的准确性。
  3024. if (box.score < MinBoxInitialScore) {
  3025. //如Xszq2fv03b的电池pano8-0其实是纸箱、 WZQoMbNmNTu的pano14-0分数0.649
  3026. return console.error('取消createSinglePano: 线框识别分数低,可能错误', box.sid, box)
  3027. }
  3028. getBoxBase(box)
  3029. let center = getBoxPos(box)
  3030. if (safeBound.distanceToPoint(center) > 0) {
  3031. return console.log('取消createSinglePano:超出safebound', box) //可能是错误的线框,如H7pg1tO9oeJ pano8-1
  3032. }
  3033. let info = {
  3034. name: box.sid,
  3035. box0: box,
  3036. center,
  3037. topPos: box.topPos,
  3038. btmPos: box.btmPos,
  3039. }
  3040. preDealBox(info)
  3041. const minScore = -500 * minScorePercent //调试 3MnIWabM6ne Tmo1vLp9Q13
  3042. let a = getPoseScore(info.boxposes, box.boxType /* true */)
  3043. if (!standards[box.boxType].bottom && box.btmPos) {
  3044. a -= (box.btmPos.y - groundY) * 3000 //底部被遮住一部分(但是像vHC1GfkdKtD在户外,容易底部变高到bound外去怎么办)
  3045. }
  3046. let failed = a < minScore
  3047. console.log('createSinglePano', failed ? '失败' : '成功', 'pose score:', a, box.sid, box)
  3048. if (failed) return
  3049. //addLabel(center, 'center', { a: 0.3 })
  3050. //info.topPos && addLabel(info.topPos, 'topPos', { a: 0.3 })
  3051. info.score = a
  3052. getBoxSize(info)
  3053. new Box(info)
  3054. }
  3055. //去除挨得很近的漫游点,因为两个接近的点match出的值误差很大
  3056. {
  3057. this.removedDatas = {}
  3058. let panoIds = Object.keys(this.datas)
  3059. let len = panoIds.length
  3060. for (let i = 0; i < len; i++) {
  3061. let pano0 = player.model.panos.index[panoIds[i]]
  3062. for (let j = i + 1; j < len; j++) {
  3063. let pano1 = player.model.panos.index[panoIds[j]]
  3064. if (pano0.position.distanceToSquared(pano1.position) < 0.01) {
  3065. //离的很近。保留shape多的那个data
  3066. let remove
  3067. if (this.datas[panoIds[i]].shapes.length > this.datas[panoIds[j]].shapes.length) {
  3068. remove = panoIds[j]
  3069. } else {
  3070. remove = panoIds[i]
  3071. }
  3072. console.log(`删除pano${remove}的data,因pano${panoIds[i]}和pano${panoIds[j]}很近`)
  3073. this.removedDatas[remove] = this.datas[remove]
  3074. delete this.datas[remove]
  3075. }
  3076. }
  3077. }
  3078. }
  3079. //this.expandModelBound()
  3080. // if (version == 'vision') this.datasMixed = common.CloneObject(this.datas, null, [player.model.panos.list[0].constructor])
  3081. if (version == 'vision')
  3082. this.datasMixed = common.CloneObject(this.datas, null, undefined, data => {
  3083. return data['category']
  3084. })
  3085. /* Search('cabinet')
  3086. Search('air')
  3087. Search('battery') */
  3088. for (let i in typeNames) {
  3089. Search(i)
  3090. }
  3091. console.log('----FindRest----')
  3092. waitFindRest.forEach(e => {
  3093. findRest(...e.args)
  3094. if (e.type != 'air' && e.type != 'airSmart' && e.type != 'cabinet') combines(e.type)
  3095. })
  3096. combines(['air', 'airSmart']) //这两种合在一起combine,因为太像了容易识别出多个 nZrBdvRaDuC
  3097. console.log('cost:', Date.now() - startTime, 'ms, boxSolid:', this.boxesSolid)
  3098. }
  3099. /* let getSid = (function(){
  3100. let sid = 0
  3101. return function(){
  3102. return sid++
  3103. }
  3104. })() */
  3105. let done = () => {
  3106. for (let panoId in this.datas) {
  3107. if (!this.datas[panoId]) continue
  3108. this.datas[panoId].shapes = this.datas[panoId].shapes.map((shape, i) => {
  3109. return Object.assign(
  3110. {
  3111. sid: 'pano' + panoId + '-' + i,
  3112. category: shape.category, //提前 便于调试
  3113. pano: player.model.panos.index[panoId],
  3114. index: i,
  3115. },
  3116. shape
  3117. )
  3118. })
  3119. }
  3120. if (this.ifAnalyze) {
  3121. this.panoBound = new THREE.Box3()
  3122. player.model.chunks.forEach(e => {
  3123. modelBound.union(e.geometry.boundingBox) //注:不用model.boundingBox是 因为union了pano的position的
  3124. })
  3125. //针对部分模型错误,只有底面的,union一下pano.position
  3126. let minY = Infinity,
  3127. minYs = []
  3128. let panos = player.model.panos.list.filter(e => e.isAligned())
  3129. panos.forEach(e => {
  3130. let bound = new THREE.Box3().setFromCenterAndSize(e.position, new THREE.Vector3(0.1, 0.1, 0.1))
  3131. modelBound.union(bound)
  3132. this.panoBound.union(bound)
  3133. minY = Math.min(e.floorPosition.y, minY)
  3134. //avePanoFY += e.floorPosition.y
  3135. minYs.push(e.floorPosition.y)
  3136. })
  3137. groundY = modelBound.min.y
  3138. minYs.sort((a, b) => {
  3139. return a - b
  3140. })
  3141. console.log(minYs)
  3142. let midFloorY = minYs[Math.floor(minYs.length / 2)]
  3143. console.error('minY', minY, 'midFloorY', midFloorY, '原groundY', groundY)
  3144. this.minY = minY
  3145. //部分模型底部高度错误
  3146. /* if (minY > groundY) {
  3147. console.error('minY > groundY', minY, groundY)
  3148. groundY = modelBound.min.y = midFloorY //案例nZrBdvRaDuC
  3149. } else {
  3150. if (groundY - minY > 0.05) console.warn('minY', minY, 'groundY', groundY)
  3151. groundY = modelBound.min.y = midFloorY , document.title += ' new' //修改以后未必更好所以暂时不修改 变更好的:eGhyf5QdVHA
  3152. } */
  3153. groundY = modelBound.min.y = midFloorY //这个y可能不准。需要通过fire的btmPos.y来确定
  3154. safeBound = this.safeBound = modelBound
  3155. groundPlane.setFromNormalAndCoplanarPoint(new THREE.Vector3(0, 1, 0), new THREE.Vector3(0, groundY, 0))
  3156. beginCompute()
  3157. }
  3158. if (version == 'vision') this.load(player.currentPano.id)
  3159. }
  3160. async function load(panoId) {
  3161. let data = await http.post('/service/scene/sceneMarkShape/getInfo', { num: player.$app.config.num, imagePath: panoId + '.jpg' })
  3162. // console.error(data)
  3163. if (!data.data || !data.success) return (this.datas[panoId] = null)
  3164. this.datas[panoId] = data.data
  3165. if (Object.keys(this.datas).length == panosCount && !player.model.panos.list.some(e => e.isAligned() && !(panoId in this.datas))) {
  3166. done()
  3167. }
  3168. }
  3169. async function loadAll() {
  3170. let data = await http.post('/service/shapes/sceneMarkShape/getInfos', { num: player.$app.config.num })
  3171. if (!data.data || !data.success) return
  3172. if (browser.urlHasValue('ext')) {
  3173. //利用算好的toJson的数据展示框
  3174. //console.log('box8',data.data)
  3175. data.data.box8.dataSet.boxes.forEach(e => {
  3176. let point1 = math.convertVisionVector(new THREE.Vector3().fromArray(e.points[0]))
  3177. let point2 = math.convertVisionVector(new THREE.Vector3().fromArray(e.points[1]))
  3178. let point3 = math.convertVisionVector(new THREE.Vector3().fromArray(e.points[2]))
  3179. let point4 = math.convertVisionVector(new THREE.Vector3().fromArray(e.points[4]))
  3180. let size = new THREE.Vector3(point1.distanceTo(point2), point1.y - point4.y, point3.distanceTo(point2))
  3181. let center = new THREE.Vector3().addVectors(point3, point4).multiplyScalar(0.5) //对角线中点
  3182. //可能需要考虑上rotation,现暂时不需要
  3183. let box = new Box({
  3184. buildFromData: true,
  3185. center,
  3186. size,
  3187. boxType: e.type,
  3188. name: e.sid,
  3189. })
  3190. })
  3191. this.ifAnalyze = false
  3192. }
  3193. let box4 = Array.isArray(data.data) ? data.data : data.data.box4 // 兼容旧数据
  3194. box4.forEach(e => {
  3195. let panoId = e.imagePath.split('.jpg')[0]
  3196. this.datas[panoId] = e
  3197. })
  3198. done()
  3199. }
  3200. let panosCount = 0
  3201. if (!dataList) {
  3202. /* player.model.panos.list.forEach(e => {
  3203. if (!e.isAligned()) return
  3204. panosCount++
  3205. load.bind(this)(e.id)
  3206. }) */
  3207. loadAll.bind(this)() //测试环境
  3208. } else {
  3209. //when version == 'output'
  3210. dataList.forEach(e => {
  3211. let panoId = e.imagePath.split('.jpg')[0]
  3212. this.datas[panoId] = e
  3213. })
  3214. done()
  3215. }
  3216. }
  3217. expandModelBound() {
  3218. //有的模型太窄,容易将一排的柜体当做墙壁。所以可以根据box位置扩展bound. (如果因为点位太少,导致内部的电池远超模型范围,就不管了。R7xZsmm9FsG)
  3219. const maxDis0 = 1, //最终位置不会超过这个距离
  3220. maxDis1 = 3 //搜寻范围。不可扩展太宽,否则不准确的框会飘很远,甚至多画多个box,如R7xZsmm9FsG
  3221. let newBound = modelBound.clone()
  3222. let list = []
  3223. for (let panoId in this.datas) {
  3224. if (!this.datas[panoId]) continue
  3225. let { imageWidth, imageHeight } = this.datas[panoId]
  3226. this.datas[panoId].shapes.forEach(box => {
  3227. getBoxBase(box, imageWidth, imageHeight)
  3228. if (box.sid == 'pano2-10') {
  3229. console.log(4)
  3230. }
  3231. if (box.btmPosPredict) {
  3232. let far = box.pano.position.distanceToSquared(box.btmPosPredict)
  3233. if (far > 20) return //太远不准
  3234. let dis = modelBound.distanceToPoint(box.btmPosPredict)
  3235. if (dis > 0 && dis < maxDis1) {
  3236. //maxDis1用来防air-hanging和一些错误的框
  3237. list.push({ box, dis })
  3238. }
  3239. }
  3240. })
  3241. }
  3242. list.sort((a, b) => a.dis - b.dis)
  3243. //let mid = list[Math.floor(list.length/2)]
  3244. let mid = list.length // /2
  3245. for (let i = 0; i < mid; i++) {
  3246. let box = list[i].box
  3247. let pos = box.btmPosPredict
  3248. if (list[i].dis > maxDis0) {
  3249. let p1 = pos.clone().clamp(modelBound.min, modelBound.max)
  3250. let vec = new THREE.Vector3().subVectors(pos, p1).normalize().multiplyScalar(maxDis0)
  3251. pos = new THREE.Vector3().addVectors(p1, vec)
  3252. }
  3253. let marginBound = new THREE.Box3().setFromCenterAndSize(pos, new THREE.Vector3(0.2, 0, 0.2))
  3254. newBound.union(marginBound)
  3255. }
  3256. skyBoxTight = new BoundingMesh(
  3257. newBound,
  3258. new THREE.MeshBasicMaterial({
  3259. side: THREE.DoubleSide,
  3260. wireframe: true,
  3261. transparent: true,
  3262. opacity: 0.05,
  3263. }),
  3264. 0
  3265. )
  3266. //skyBoxTight.visible = false
  3267. skyBoxTight.updateMatrixWorld() //不update的话raycaster是错的
  3268. meshGroup.add(skyBoxTight)
  3269. this.skyBoxTight = skyBoxTight
  3270. this.safeBound = this.safeBoundFirstVer = safeBound = newBound
  3271. boundConfirmed = true
  3272. console.log('bound1:', this.safeBound.min.toArray(), this.safeBound.max.toArray())
  3273. }
  3274. expandModelBound2(type) {
  3275. let material = skyBoxTight.material
  3276. skyBoxTight.geometry.dispose()
  3277. boxesSolid.forEach(e => {
  3278. if (e.boxType != type) return
  3279. this.safeBound.union(e.bound)
  3280. })
  3281. skyBoxTight = new BoundingMesh(this.safeBound, material, 0)
  3282. //skyBoxTight.visible = false
  3283. skyBoxTight.updateMatrixWorld() //不update的话raycaster是错的
  3284. meshGroup.add(skyBoxTight)
  3285. this.skyBoxTight = skyBoxTight
  3286. console.log('bound2:', this.safeBound.min.toArray(), this.safeBound.max.toArray())
  3287. }
  3288. /* adjustModelBound(type){
  3289. if(standards[type].atWall != 1)return //必须是挂墙的
  3290. this.lastSafeBound = this.safeBound.clone()
  3291. let list = []
  3292. let add = e => {
  3293. if (e.btmPos && e.box1 && e.minAng>10 ) {
  3294. //有 box1才能确定是getIntersect得到的pos
  3295. list.includes(e) || e.push(e)
  3296. }
  3297. }
  3298. this.boxesSolid.forEach((solidBox)=>{
  3299. if(solidBox.boxType != type)return
  3300. solidBox.traversePair(add)
  3301. })
  3302. let wallSides = {'x+': 0, 'x-': 0, 'z+': 0, 'z-': 0}
  3303. let getBoxSide = (e)=>{
  3304. for(let i in e.panosDir){
  3305. if(e.panosDir[i] != 0){
  3306. wallSides[i] += 1
  3307. }
  3308. }
  3309. }
  3310. if(list.length){
  3311. this.safeBound = this.panoBound.clone()
  3312. list.forEach((e)=>{
  3313. this.safeBound.union(e.bound)//还是说使用cIntersect来expand?
  3314. getBoxSide()
  3315. })
  3316. }
  3317. skyBoxTight = new BoundingMesh(this.safeBound, material, 0)
  3318. //skyBoxTight.visible = false
  3319. skyBoxTight.updateMatrixWorld() //不update的话raycaster是错的
  3320. meshGroup.add(skyBoxTight)
  3321. this.skyBoxTight = skyBoxTight
  3322. //主要目的,针对那些模型比room大得多的情况,比如多了门外的部分,造成墙面不准。
  3323. //monitor的可以完全决定位置。其他的只能收缩(但是不能收缩超过panos和第一次expand的那些btm的bound里)
  3324. //太麻烦了,且考虑到即使墙面完全准确也可能反倒把它变的不准的风险。
  3325. } */
  3326. /* 最低点使用fire的吗
  3327. MW6MEeCOy9Y 只有最近三个点和fire接近
  3328. 3MnIWabM6ne fire combine了
  3329. ov5NTEImzhW fire多个
  3330. n4z0yd5tQaF fire多两个错位离谱的。。 位置和显示的不一样。。
  3331. 5BaiXkK6Ag1 fire算的不太准 低了0.1 样本数仅两个
  3332. */
  3333. confirmGroundY(type) {
  3334. //利用fire来确定地面高度(会稍低于地板,但box框不打滑且xz更准,估计因box框比box大)。调试:3MnIWabM6ne up9PPZkx1px 4GqaqNdyjGfs GFbQi1LiSij
  3335. if (boundConfirmed) return
  3336. let btmYs = [],
  3337. pairs = [],
  3338. needCount = 5,
  3339. maxDis = 3,
  3340. btmY = 0
  3341. let add = e => {
  3342. if (e.btmPos && e.box1 /* && e.score >= minScore */) {
  3343. //有 box1才能确定是getIntersect得到的pos
  3344. pairs.push(e)
  3345. }
  3346. }
  3347. boxesSolid.forEach(e => {
  3348. if (e.boxType != type) return
  3349. e.traversePair(add)
  3350. })
  3351. let usePairs = pairs
  3352. if (pairs.length > needCount) {
  3353. //调试:Y8czF2Z3h9m
  3354. let disMap = new Map()
  3355. pairs.forEach(e => {
  3356. disMap.set(e, Math.max(e.box0.pano.position.distanceTo(e.box0.btmPosPredict), e.box1.pano.position.distanceTo(e.box1.btmPosPredict)))
  3357. })
  3358. pairs.sort((a, b) => {
  3359. return disMap.get(a) - disMap.get(b)
  3360. }) //距离从近到远 . 远处的高度可能偏离严重,就不管了,而且框也不一定准
  3361. usePairs = pairs.slice(0, needCount)
  3362. for (let i = needCount; i < pairs.length; i++) {
  3363. if (disMap.get(pairs[i]) < maxDis) {
  3364. usePairs.push(pairs[i])
  3365. }
  3366. }
  3367. }
  3368. usePairs.forEach(e => {
  3369. //有 box1才能确定是getIntersect得到的pos
  3370. let btmY_ = e.btmPos.y
  3371. const width = e.size.x / 2
  3372. let h0 = width / Math.tan(Math.acos(-e.box0.centerBtmDir.y)) //|centerBtmDir.y| 即俯视角度的cos
  3373. let h1 = width / Math.tan(Math.acos(-e.box1.centerBtmDir.y))
  3374. let h = Math.min(h0, h1) //选个小的吧,因浅的会更快接触到中心,虽然交点是两条射线最近点 不一定在fire中心
  3375. //如果毫无误差,且centerBtmDir.y相同,只要两条线centerBtmDir的xz相同,交点就是和地面的交点,而只要不同,交点就是和地面的交点,而只要不同,交点必然是在fire中心之下。随着minAng和centerBtmDir.y 交点在这中间变化
  3376. let r = math.linearClamp(e.minAng, 0, 90, 0, 1)
  3377. btmY_ += h * r
  3378. btmYs.push(btmY_)
  3379. btmY += btmY_
  3380. })
  3381. btmY /= btmYs.length
  3382. if (btmYs.length) {
  3383. console.error(
  3384. 'confirmGroundY',
  3385. btmY,
  3386. /* '样本数', btmYs.length, */ btmYs,
  3387. usePairs.map(e => e.name),
  3388. pairs
  3389. )
  3390. /* if(btmYs.length == 1 && pairs[0].minAngle<12 && ){
  3391. } */
  3392. groundY = this.safeBound.min.y = this.panoBound.min.y = btmY // = -1.1
  3393. groundPlane.setFromNormalAndCoplanarPoint(new THREE.Vector3(0, 1, 0), new THREE.Vector3(0, groundY, 0))
  3394. }
  3395. let { min, max } = standards[type].height
  3396. boxesSolid.slice().forEach(e => {
  3397. if (e.boxType != type) return
  3398. if (e.fake) {
  3399. e.dispose()
  3400. return
  3401. }
  3402. let topY = e.topPos
  3403. ? e.topPos.y
  3404. : e.list.reduce((w, c) => {
  3405. return w + c.topPos.y
  3406. }, 0) / e.list.length
  3407. e.size.y = THREE.MathUtils.clamp(topY - groundY, min, max)
  3408. e.setFromInfo(e)
  3409. if (version == 'vision') e.draw()
  3410. })
  3411. this.panoBound
  3412. this.expandModelBound()
  3413. }
  3414. bindEvents() {
  3415. if (version != 'vision') return
  3416. player.on(PlayerEvents.FlyingStarted, e => {
  3417. //if(e.mode == 'dollhouse')return
  3418. // 点位跳转前清除已有线框
  3419. this.traverse(obj => {
  3420. if (obj.isMesh) {
  3421. obj.geometry.dispose()
  3422. obj.material.dispose()
  3423. }
  3424. })
  3425. this.wireframes.clear()
  3426. this.currentId = null
  3427. })
  3428. player.on(PlayerEvents.FlyingEnded, () => {
  3429. // 点位跳转后加载线框
  3430. if (player.mode != Viewmode.PANORAMA) return // 只有PANORAMA模式下需要加载
  3431. this.load(player.currentPano.id)
  3432. })
  3433. global.boxFrame = this
  3434. if (this.ifAnalyze) {
  3435. setTimeout(() => {
  3436. {
  3437. let btn = document.createElement('button')
  3438. btn.innerHTML = '点击切换box显示'
  3439. btn.onclick = () => {
  3440. this.boxesSolid.forEach(e => ((e.boxHelper.visible = !e.boxHelper.visible), (e.label.visible = !e.label.visible)))
  3441. }
  3442. document.querySelector('#app').appendChild(btn)
  3443. btn.id = 'boxWire'
  3444. btn.style.position = 'fixed'
  3445. btn.style['z-index'] = '100'
  3446. btn.style.background = '#e00472'
  3447. btn.style.padding = '10px'
  3448. btn.style.bottom = '80px'
  3449. }
  3450. {
  3451. let btn = document.createElement('button')
  3452. btn.innerHTML = '点击切换矩形框显示'
  3453. btn.onclick = () => {
  3454. this.wireframes.visible = !this.wireframes.visible
  3455. }
  3456. document.querySelector('#app').appendChild(btn)
  3457. btn.id = 'wireframes'
  3458. btn.style.position = 'fixed'
  3459. btn.style['z-index'] = '100'
  3460. btn.style.background = '#419aff'
  3461. btn.style.padding = '10px'
  3462. btn.style.bottom = '130px'
  3463. }
  3464. }, 1000)
  3465. }
  3466. }
  3467. /**
  3468. * 加载点位标记数据
  3469. * @param {*} panoId
  3470. */
  3471. load(panoId) {
  3472. let data = this.datasMixed[panoId] || this.datas[panoId]
  3473. if (!data) {
  3474. if (!(panoId in this.datas))
  3475. setTimeout(() => {
  3476. this.load(panoId)
  3477. }, 100) //否则无数据
  3478. return
  3479. }
  3480. if (player.currentPano.id != panoId || player.flying || this.currentId == panoId) return // 防止连续跳转点位时,clear后才load好上一点位的数据,导致出现之前的标记
  3481. this.currentId = panoId
  3482. let { shapes, imageHeight, imageWidth } = data //data.data
  3483. let allShapes = shapes.slice()
  3484. shapes.forEach(e => {
  3485. if (e.boxes) allShapes.push(...e.boxes)
  3486. })
  3487. let fireIndex = 0
  3488. allShapes.forEach(shape => {
  3489. // 填充色和线框色
  3490. // let { fill_color, line_color } = shape
  3491. getUVs(shape)
  3492. getCenterDir(shape, player.currentPano)
  3493. let { fill_color, color = [56, 56, 255] } = shape
  3494. let line_color = [...color, 255]
  3495. if (!fill_color) fill_color = [255, 255, 255, 0]
  3496. if (!line_color) line_color = [255, 0, 0, 255]
  3497. if (shape.boxes) {
  3498. line_color = [20, 205, 255, 255]
  3499. }
  3500. let pos = getBoxPos(shape)
  3501. let dis = pos ? shape.pano.position.distanceTo(getBoxPos(shape)) : 1
  3502. let labelShift = (shape.boxType == 'fire' ? 0 : -0.2) / dis
  3503. let name = shape.category + '-' + shape.sid
  3504. //if(shape.score < MinBoxInitialScore){
  3505. name = [name, 'sc: ' + math.toPrecision(shape.score, 3)]
  3506. //}
  3507. this.showSignalFrom2d(
  3508. name,
  3509. shape.bbox2,
  3510. imageWidth,
  3511. imageHeight,
  3512. {
  3513. fill: {
  3514. color: new THREE.Color().setRGB(fill_color[0] / 255, fill_color[1] / 255, fill_color[2] / 255),
  3515. opacity: fill_color[3] / 255,
  3516. },
  3517. line: {
  3518. color: new THREE.Color().setRGB(line_color[0] / 255, line_color[1] / 255, line_color[2] / 255),
  3519. opacity: shape.category == 'cabling_rack' ? 0.4 : line_color[3] / 255, //走线架太绕,扰乱视线
  3520. },
  3521. },
  3522. shape.centerDir,
  3523. labelShift,
  3524. shape.state == '被删除'
  3525. )
  3526. })
  3527. // })
  3528. // .catch(err => console.log(`点位${panoId}无标记数据或数据出错:`, err))
  3529. }
  3530. /**
  3531. * 根据坐标标记全景图
  3532. *
  3533. * 存在的问题:如果要准确复现全景图上的线框,上下边框会变为弧形。而按顶点连直线的话,180度以上会出bug。
  3534. * 解决方式:目前150度以下只画出4个顶点然后连直线,150度以上准确画出全景图线框。
  3535. */
  3536. showSignalFrom2d(name, rect, w, h, options, centerDir, labelShift, removed) {
  3537. // 目前rect给的是矩形对角的两个点坐标,将它扩展成四个顶点
  3538. let cornerArr = [new THREE.Vector2(rect[0], rect[1]), new THREE.Vector2(rect[2], rect[1]), new THREE.Vector2(rect[2], rect[3]), new THREE.Vector2(rect[0], rect[3])]
  3539. // 根据四个顶点,填充中间点
  3540. let pointArr = []
  3541. for (let i = 0; i < cornerArr.length; i++) {
  3542. let corner1 = cornerArr[i]
  3543. let corner2 = cornerArr[(i + 1) % cornerArr.length]
  3544. pointArr.push(corner1)
  3545. /* // 横向角度超过150度时,3d中边框的弧线已经不太明显,准确画出全景图线框
  3546. if ((rect[2] - rect[0]) / w < 5 / 12 && i % 2 == 0) continue
  3547. const vec = [corner2[0] - corner1[0], corner2[1] - corner1[1]]
  3548. let length = Math.sqrt(vec[0] * vec[0] + vec[1] * vec[1])
  3549. let num = length / 150
  3550. for (let j = 1; j <= num; j++) {
  3551. pointArr.push([corner1[0] + (vec[0] / num) * j, corner1[1] + (vec[1] / num) * j])
  3552. } */
  3553. }
  3554. //pointArr.push(cornerArr[0], cornerArr[2], cornerArr[1], cornerArr[3]) //对角线
  3555. let points = []
  3556. pointArr.forEach(uv => {
  3557. let dir = getDirByUV(uv, player.currentPano)
  3558. // points.push(dir.sub(centerVec)) // 计算其他点相对于中点的坐标,方便旋转平移等
  3559. points.push(dir)
  3560. })
  3561. // 线框
  3562. const lineGeometry = new THREE.BufferGeometry().setFromPoints(points)
  3563. const lineMaterial = new THREE.LineBasicMaterial({ color: options.line.color, opacity: options.line.opacity, transparent: true, depthTest: false })
  3564. const wireframe = new THREE.LineLoop(lineGeometry, lineMaterial)
  3565. // wireframe.position.copy(centerVec) // 将中点作为线框坐标
  3566. wireframe.renderOrder = 100
  3567. // 填充颜色
  3568. const fillGeometry = lineGeometry.clone().setIndex(new THREE.BufferAttribute(new Uint16Array([0, 1, 3, 2, 3, 1]), 1))
  3569. const fillMaterial = new THREE.MeshBasicMaterial({ color: options.fill.color, opacity: options.fill.opacity, transparent: true, side: THREE.DoubleSide, depthTest: false })
  3570. const plane = new THREE.Mesh(fillGeometry, fillMaterial)
  3571. plane.renderOrder = wireframe.renderOrder - 1
  3572. wireframe.add(plane)
  3573. // 名称
  3574. const textMesh = new TextSprite({
  3575. text: name,
  3576. backgroundColor: { r: options.line.color.r * 255, g: options.line.color.g * 255, b: options.line.color.b * 255, a: options.line.opacity * 0.5 },
  3577. textColor: { r: 255, g: 255, b: 255, a: options.line.opacity * 1.1 },
  3578. borderRadius: 15,
  3579. renderOrder: wireframe.renderOrder + 1,
  3580. player: player,
  3581. })
  3582. //const shift = new THREE.Vector3(0, labelShift , 0)
  3583. textMesh.position.copy(centerDir /* .clone().add(shift).normalize() */)
  3584. textMesh.lookAt(0, 0, 0) // 看向相机
  3585. textMesh.scale.set(0.12, 0.12, 0.12)
  3586. /* let line = addLine(centerDir, shift, null, options.line.color)
  3587. line.material.opacity = options.line.opacity */
  3588. let group = new THREE.Group()
  3589. group.position.copy(player.currentPano.position)
  3590. group.add(wireframe)
  3591. group.add(textMesh)
  3592. //group.add(line)
  3593. this.wireframes.add(group)
  3594. if (removed) {
  3595. textMesh.sprite.material.opacity = 0.4
  3596. lineMaterial.opacity *= 0.6
  3597. lineMaterial.color.set('#efe')
  3598. }
  3599. }
  3600. clear() {
  3601. //清除上一次的结果
  3602. ;(skyBoxTight = null), (meshGroup = null), (modelBound = new THREE.Box3()), (groundY = null), (safeBound = null), (boundConfirmed = null), (hue = 0), (boxesSolid = [])
  3603. }
  3604. }