PanoBoxFrame.js 173 KB

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