PanoBoxFrame.js 146 KB

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