text,length,is_long_context,metric_val,label_metric "---- Integer Integer FP funct3 funct3 funct3 OPIVV V OPMVV V OPFVV V OPIVX X OPMVX X OPFVF F OPIVI I funct6 funct6 funct6 000000 VXI vadd 000000 V vredsum 000000 VF vfadd 000001 000001 V vredand 000001 V vfredsum 000010 VX vsub 000010 V vredor 000010 VF vfsub 000011 XI vrsub 000011 V vredxor 000011 V vfredosum 000100 VX vminu 000100 V vredminu 000100 VF vfmin 000101 VX vmin 000101 V vredmin 000101 V vfredmin 000110 VX vmaxu 000110 V vredmaxu 000110 VF vfmax 000111 VX vmax 000111 V vredmax 000111 V vfredmax 001000 001000 001000 VF vfsgnj 001001 VXI vand 001001 001001 VF vfsgnn 001010 VXI vor 001010 001010 VF vfsgnx 001011 VXI vxor 001011 001011 001100 VXI vrgather 001100 V vext.x.v 001100 V vfmv.f.s 001101 001101 X vmv.s.x 001101 F vfmv.s.f 001110 XI vslideup 001110 X vslide1up 001110 001111 XI vslidedown 001111 X vslide1down 001111 010000 VXI vadc 010000 010000 010001 010001 010001 010010 VX vsbc 010010 010010 010011 010011 010011 010100 010100 V vmpopc 010100 010101 010101 V vmfirst 010101 010110 010110 V VMUNARY0 010110 010111 VXI vmerge 010111 V vcompress 010111 F vfmerge.vf 011000 VXI vseq 011000 V vmandnot 011000 VF vfeq 011001 VXI vsne 011001 V vmand 011001 VF vflte 011010 VX vsltu 011010 V vmor 011010 VF vford 011011 VX vslt 011011 V vmxor 011011 VF vflt 011100 VXI vsleu 011100 V vmornot 011100 VF vfne 011101 VXI vsle 011101 V vmnand 011101 F vfgt 011110 XI vsgtu 011110 V vmnor 011110 011111 XI vsgt 011111 V vmxnor 011111 F vfgte 100000 VXI vsaddu 100000 VX vdivu 100000 VF vfdiv 100001 VXI vsadd 100001 VX vdiv 100001 F vfrdiv 100010 VX vssubu 100010 VX vremu 100010 V VFUNARY0 100011 VX vssub 100011 VX vrem 100011 V VFUNARY1 100100 VXI vaadd 100100 VX vmulhu 100100 VF vfmul 100101 VXI vsll 100101 VX vmul 100101 100110 VX vasub 100110 VX vmulhsu 100110 100111 VX vsmul 100111 VX vmulh 100111 101000 VXI vsrl 101000 101000 VF vfmadd 101001 VXI vsra 101001 VX vmadd 101001 VF vfnmadd 101010 VXI vssrl 101010 101010 VF vfmsub 101011 VXI vssra 101011 VX vmsub 101011 VF vfnmsub 101100 VXI vnsrl 101100 101100 VF vfmacc 101101 VXI vnsra 101101 VX vmacc 101101 VF vfnmacc 101110 VXI vnclipu 101110 101110 VF vfmsac 101111 VXI vnclip 101111 VX vmsac 101111 VF vfnmsac 110000 V vwredsumu 110000 VX vwaddu 110000 VF vfwadd 110001 V vwredsum 110001 VX vwadd 110001 V vfwredsum 110010 110010 VX vwsubu 110010 VF vfwsub 110011 110011 VX vwsub 110011 V vfwredosum 110100 110100 VX vwaddu.w 110100 VF vfwadd.w 110101 110101 VX vwadd.w 110101 110110 110110 VX vwsubu.w 110110 VF vfwsub.w 110111 110111 VX vwsub.w 110111 111000 V vdotu 111000 VX vwmulu 111000 VF vfwmul 111001 V vdot 111001 111001 V vfdot 111010 111010 VX vwmulsu 111010 111011 111011 VX vwmul 111011 111100 VX vwsmaccu 111100 VX vwmaccu 111100 VF vfwmacc 111101 VX vwsmacc 111101 VX vwmacc 111101 VF vfwnmacc 111110 VX vwsmsacu 111110 VX vwmsacu 111110 VF vfwmsac 111111 VX vwsmsac 111111 VX vwmsac 111111 VF vfwnmsac ---- ---- VFUNARY0 encoding space vs1 single-width converts 00000 vfcvt.xu.f.v 00001 vfcvt.x.f.v 00010 vfcvt.f.xu.v 00011 vfcvt.f.x.v widening converts 01000 vfwcvt.xu.f.v 01001 vfwcvt.x.f.v 01010 vfwcvt.f.xu.v 01011 vfwcvt.f.x.v 01100 vfwcvt.f.f.v narrowing converts 10000 vfncvt.xu.f.v 10001 vfncvt.x.f.v 10010 vfncvt.f.xu.v 10011 vfncvt.f.x.v 10100 vfncvt.f.f.v ---- ---- VFUNARY1 encoding space vs1 00000 vfsqrt.v 10000 vfclass.v ---- ---- VMUNARY0 encoding space vs1 00001 vmsbf 00010 vmsof 00011 vmsif 10000 vmiota 10001 vid ---- //// .Vector Unit-Stride Load/Store Instruction Listing [width=""100%"",cols=""^3,^3,^3,^4,^4,^3,^3,^3,^7,<10""] |======================== |31 30 |29 27 |26 25 |24 20 |19 15 |14 12 |11 10 |9 7 |6 0 |Opcode |off[1:0]|000|vm|00000|rs1|000 2+|vd|0000111|VLBU.V |off[1:0]|000|vm|00000|rs1|101 2+|vd|0000111|VLHU.V |off[1:0]|000|vm|00000|rs1|110 2+|vd|0000111|VLWU.V |off[1:0]|000|vm|00000|rs1|111 2+|vd|0000111|VLE.V |off[1:0]|100|vm|00000|rs1|000 2+|vd|0000111|VLB.V |off[1:0]|100|vm|00000|rs1|101 2+|vd|0000111|VLH.V |off[1:0]|100|vm|00000|rs1|110 2+|vd|0000111|VLW.V 2+|vs3|vm|00000|rs1|000|off[1:0]|000|0100111|VSB.V 2+|vs3|vm|00000|rs1|101|off[1:0]|000|0100111|VSH.V 2+|vs3|vm|00000|rs1|110|off[1:0]|000|0100111|VSW.V 2+|vs3|vm|00000|rs1|111|off[1:0]|000|0100111|VSE.V |======================== .Vector Unit-Stride Fault-First Load Instruction Listing [width=""100%"",cols=""^3,^3,^3,^4,^4,^3,^3,^3,^7,<10""] |======================== |31 30 |29 27 |26 25 |24 20 |19 15 |14 12 |11 10 |9 7 |6 0 |Opcode |off[1:0]|000|vm|10000|rs1|000 2+|vd|0000111|VLBUFF.V |off[1:0]|000|vm|10000|rs1|101 2+|vd|0000111|VLHUFF.V |off[1:0]|000|vm|10000|rs1|110 2+|vd|0000111|VLWUFF.V |off[1:0]|000|vm|10000|rs1|111 2+|vd|0000111|VLEFF.V |off[1:0]|100|vm|10000|rs1|000 2+|vd|0000111|VLBFF.V |off[1:0]|100|vm|10000|rs1|101 2+|vd|0000111|VLHFF.V |off[1:0]|100|vm|10000|rs1|110 2+|vd|0000111|VLWFF.V |======================== .Vector Strided Load/Store Instruction Listing [width=""100%"",cols=""^3,^3,^3,^4,^4,^3,^3,^3,^7,<10""] |======================== |31 30 |29 27 |26 25 |24 20 |19 15 |14 12 |11 10 |9 7 |6 0 |Opcode |off[1:0]|010|vm|rs2|rs1|000 2+|vd|0000111|VLSBU.V |off[1:0]|010|vm|rs2|rs1|101 2+|vd|0000111|VLSHU.V |off[1:0]|010|vm|rs2|rs1|110 2+|vd|0000111|VLSWU.V |off[1:0]|010|vm|rs2|rs1|111 2+|vd|0000111|VLSE.V |off[1:0]|110|vm|rs2|rs1|000 2+|vd|0000111|VLSB.V |off[1:0]|110|vm|rs2|rs1|101 2+|vd|0000111|VLSH.V |off[1:0]|110|vm|rs2|rs1|110 2+|vd|0000111|VLSW.V 2+|vs3|vm|rs2|rs1|000|off[1:0]|010|0100111|VSSB.V 2+|vs3|vm|rs2|rs1|101|off[1:0]|010|0100111|VSSH.V 2+|vs3|vm|rs2|rs1|110|off[1:0]|010|0100111|VSSW.V 2+|vs3|vm|rs2|rs1|111|off[1:0]|010|0100111|VSSE.V |======================== .Vector Indexed Load/Store Instruction Listing [width=""100%"",cols=""^3,^3,^3,^4,^4,^3,^3,^3,^7,<10""] |======================== |31 30 |29 27 |26 25 |24 20 |19 15 |14 12 |11 10 |9 7 |6 0 |Opcode |off[1:0]|011|vm|vs2|rs1|000 2+|vd|0000111|VLXBU.V |off[1:0]|011|vm|vs2|rs1|101 2+|vd|0000111|VLXHU.V |off[1:0]|011|vm|vs2|rs1|110 2+|vd|0000111|VLXWU.V |off[1:0]|011|vm|vs2|rs1|111 2+|vd|0000111|VLXE.V |off[1:0]|111|vm|vs2|rs1|000 2+|vd|0000111|VLXB.V |off[1:0]|111|vm|vs2|rs1|101 2+|vd|0000111|VLXH.V |off[1:0]|111|vm|vs2|rs1|110 2+|vd|0000111|VLXW.V 2+|vs3|vm|vs2|rs1|000|off[1:0]|011|0100111|VSXB.V 2+|vs3|vm|vs2|rs1|101|off[1:0]|011|0100111|VSXH.V 2+|vs3|vm|vs2|rs1|110|off[1:0]|011|0100111|VSXW.V 2+|vs3|vm|vs2|rs1|111|off[1:0]|011|0100111|VSXE.V 2+|vs3|vm|vs2|rs1|000|off[1:0]|111|0100111|VSUXB.V 2+|vs3|vm|vs2|rs1|101|off[1:0]|111|0100111|VSUXH.V 2+|vs3|vm|vs2|rs1|110|off[1:0]|111|0100111|VSUXW.V 2+|vs3|vm|vs2|rs1|111|off[1:0]|111|0100111|VSUXE.V |======================== //// //// X vsgteu X vsgte vx4muladd vx4mulsub .Vector Table [width=""100%"",cols=""^3,^3,^3,^4,^4,^3,^3,^3,^7,<10""] |======================== 2+|31 27|26 25 |24 20 |19 15 |14 12 2+|11 7 |6 0 |Opcode 2+|00000|vm |vs2 |vs1 |001 2+|vd |1010111|VADD.VV 2+|00000|vm |vs2 |vs1 |000 2+|vd |1010111|VADD.VS 2+|00000|vm |vs2 |rs1 |010 2+|vd |1010111|VADD.VX 2+|00000|vm |vs2 |simm[4:0]|011 2+|vd |1010111|VADD.VI |======================== .Vector Table [width=""100%"",cols=""^3,^3,^3,^4,^4,^3,^3,^3,^7,<10""] |======================== |31 30 |29 27 |26 25 |24 20 |19 15 |14 12 |11 10 |9 7 |6 0 |Opcode 2+|00000|vm|vs2|vs1|000 2+|vd|1010111|VADD.VV 2+|00000|vm|vs2|vs1|100 2+|vd|1010111|VADD.VS 2+|00000|vm|imm[4:0]|vs1|101 2+|vd|1010111|VADD.VI 2+|00000|vm|vs2|vs1|010 2+|vd|1010111|VADDW.VV 2+|00000|vm|vs2|vs1|110 2+|vd|1010111|VADDW.VS 2+|00000|vm|vs2|vs1|011 2+|vd|1010111|VADDW.WV 2+|00000|vm|vs2|vs1|111 2+|vd|1010111|VADDW.WS 2+|00001|vm|vs2|vs1|000 2+|vd|1010111|VSUB.VV 2+|00001|vm|vs2|vs1|100 2+|vd|1010111|VSUB.VS 2+|00001|vm|imm[4:0]|vs1|101 2+|vd|1010111|VSUB.VI 2+|00001|vm|vs2|vs1|000 2+|vd|1010111|VSUB.VV 2+|00001|vm|vs2|vs1|100 2+|vd|1010111|VSUB.VS 2+|00001|vm|vs2|vs1|011 2+|vd|1010111|VSUBW.WV 2+|00001|vm|vs2|vs1|111 2+|vd|1010111|VSUBW.WS 2+|01000|vm|vs2|vs1|000 2+|vd|1010111|VMUL.VV 2+|01000|vm|vs2|vs1|100 2+|vd|1010111|VMUL.VS 2+|01000|vm|imm[4:0]|vs1|101 2+|vd|1010111|VMUL.VI 2+|01000|vm|vs2|vs1|000 2+|vd|1010111|VMUL.VV 2+|01000|vm|vs2|vs1|100 2+|vd|1010111|VMUL.VS 2+|01000|vm|vs2|vs1|011 2+|vd|1010111|VMULW.WV 2+|01000|vm|vs2|vs1|111 2+|vd|1010111|VMULW.WS 2+|01001|vm|vs2|vs1|000 2+|vd|1010111|VMULU.VV 2+|01001|vm|vs2|vs1|100 2+|vd|1010111|VMULU.VS 2+|01001|vm|imm[4:0]|vs1|101 2+|vd|1010111|VMULU.VI 2+|01001|vm|vs2|vs1|000 2+|vd|1010111|VMULU.VV 2+|01001|vm|vs2|vs1|100 2+|vd|1010111|VMULU.VS 2+|01001|vm|vs2|vs1|011 2+|vd|1010111|VMULUW.WV 2+|01001|vm|vs2|vs1|111 2+|vd|1010111|VMULUW.WS 2+|01010|vm|vs2|vs1|000 2+|vd|1010111|VMULSU.VV 2+|01010|vm|vs2|vs1|100 2+|vd|1010111|VMULSU.VS 2+|01010|vm|imm[4:0]|vs1|101 2+|vd|1010111|VMULSU.VI 2+|01010|vm|vs2|vs1|000 2+|vd|1010111|VMULSU.VV 2+|01010|vm|vs2|vs1|100 2+|vd|1010111|VMULSU.VS 2+|01010|vm|vs2|vs1|011 2+|vd|1010111|VMULSUW.WV 2+|01010|vm|vs2|vs1|111 2+|vd|1010111|VMULSUW.WS |======================== .Vector Table [width=""100%"",cols=""^3,^3,^3,^4,^4,^3,^3,^3,^7,<10""] |======================== |31 30 |29 27 |26 25 |24 20 |19 15 |14 12 |11 10 |9 7 |6 0 |Opcode 2+|00100|vm|vs2|vs1|000 2+|vd|1010111|VSRLN.VV 2+|00100|vm|vs2|vs1|100 2+|vd|1010111|VSRLN.VS 2+|00100|vm|imm[4:0]|vs1|101 2+|vd|1010111|VSRLN.VI 2+|00100|vm|vs2|vs1|010 2+|vd|1010111|VSRLN.WV 2+|00100|vm|vs2|vs1|110 2+|vd|1010111|VSRLN.WS 2+|00100|vm|vs2|vs1|111 2+|vd|1010111|VSRLN.WI 2+|00101|vm|vs2|vs1|000 2+|vd|1010111|VSRAN.VV 2+|00101|vm|vs2|vs1|100 2+|vd|1010111|VSRAN.VS 2+|00101|vm|imm[4:0]|vs1|101 2+|vd|1010111|VSRAN.VI 2+|00101|vm|vs2|vs1|010 2+|vd|1010111|VSRAN.WV 2+|00101|vm|vs2|vs1|110 2+|vd|1010111|VSRAN.WS 2+|00101|vm|vs2|vs1|111 2+|vd|1010111|VSRAN.WI 2+|00110|vm|vs2|vs1|000 2+|vd|1010111|VCLIPN.VV 2+|00110|vm|vs2|vs1|100 2+|vd|1010111|VCLIPN.VS 2+|00110|vm|imm[4:0]|vs1|101 2+|vd|1010111|VCLIPN.VI 2+|00110|vm|vs2|vs1|010 2+|vd|1010111|VCLIPN.WV 2+|00110|vm|vs2|vs1|110 2+|vd|1010111|VCLIPN.WS 2+|00110|vm|vs2|vs1|111 2+|vd|1010111|VCLIPN.WI 2+|00111|vm|vs2|vs1|000 2+|vd|1010111|VCLIPUN.VV 2+|00111|vm|vs2|vs1|100 2+|vd|1010111|VCLIPUN.VS 2+|00111|vm|imm[4:0]|vs1|101 2+|vd|1010111|VCLIPUN.VI 2+|00111|vm|vs2|vs1|010 2+|vd|1010111|VCLIPUN.WV 2+|00111|vm|vs2|vs1|110 2+|vd|1010111|VCLIPUN.WS 2+|00111|vm|vs2|vs1|111 2+|vd|1010111|VCLIPUN.WI 2+|10000|vm|vs2|vs1|000 2+|vd|1010111|VAND.VV 2+|10000|vm|vs2|vs1|100 2+|vd|1010111|VAND.VS 2+|10000|vm|imm[4:0]|vs1|101 2+|vd|1010111|VAND.VI 2+|10000|vm|vs2|vs1|010 2+|vd|1010111|VOR.VV 2+|10000|vm|vs2|vs1|110 2+|vd|1010111|VOR.VS 2+|10000|vm|imm[4:0]|vs1|111 2+|vd|1010111|VOR.VI 2+|10001|vm|vs2|vs1|000 2+|vd|1010111|VXOR.VV 2+|10001|vm|vs2|vs1|100 2+|vd|1010111|VXOR.VS 2+|10001|vm|imm[4:0]|vs1|101 2+|vd|1010111|VXOR.VI 2+|10010|vm|vs2|vs1|000 2+|vd|1010111|VSLL.VV 2+|10010|vm|vs2|vs1|100 2+|vd|1010111|VSLL.VS 2+|10010|vm|imm[4:0]|vs1|101 2+|vd|1010111|VSLL.VI 2+|10011|vm|vs2|vs1|000 2+|vd|1010111|VSRL.VV 2+|10011|vm|vs2|vs1|100 2+|vd|1010111|VSRL.VS 2+|10011|vm|imm[4:0]|vs1|101 2+|vd|1010111|VSRL.VI 2+|10011|vm|vs2|vs1|010 2+|vd|1010111|VSRA.VV 2+|10011|vm|vs2|vs1|110 2+|vd|1010111|VSRA.VS 2+|10011|vm|imm[4:0]|vs1|111 2+|vd|1010111|VSRA.VI 2+|10100|vm|vs2|vs1|000 2+|vd|1010111|VSEQ.VV 2+|10100|vm|vs2|vs1|100 2+|vd|1010111|VSEQ.VS 2+|10100|vm|imm[4:0]|vs1|101 2+|vd|1010111|VSEQ.VI 2+|10100|vm|vs2|vs1|010 2+|vd|1010111|VSNE.VV 2+|10100|vm|vs2|vs1|110 2+|vd|1010111|VSNE.VS 2+|10100|vm|imm[4:0]|vs1|111 2+|vd|1010111|VSNE.VI 2+|10101|vm|vs2|vs1|000 2+|vd|1010111|VSLT.VV 2+|10101|vm|vs2|vs1|100 2+|vd|1010111|VSLT.VS 2+|10101|vm|imm[4:0]|vs1|101 2+|vd|1010111|VSLT.VI 2+|10101|vm|vs2|vs1|010 2+|vd|1010111|VSLTU.VV 2+|10101|vm|vs2|vs1|110 2+|vd|1010111|VSLTU.VS 2+|10101|vm|imm[4:0]|vs1|111 2+|vd|1010111|VSLTU.VI 2+|10110|vm|vs2|vs1|000 2+|vd|1010111|VSLE.VV 2+|10110|vm|vs2|vs1|100 2+|vd|1010111|VSLE.VS 2+|10110|vm|imm[4:0]|vs1|101 2+|vd|1010111|VSLE.VI 2+|10110|vm|vs2|vs1|010 2+|vd|1010111|VSLEU.VV 2+|10110|vm|vs2|vs1|110 2+|vd|1010111|VSLEU.VS 2+|10110|vm|imm[4:0]|vs1|111 2+|vd|1010111|VSLEU.VI 2+|11000|vm|vs2|vs1|000 2+|vd|1010111|VMULH.VV 2+|11000|vm|vs2|vs1|100 2+|vd|1010111|VMULH.VS 2+|11000|vm|imm[4:0]|vs1|101 2+|vd|1010111|VMULH.VI 2+|11001|vm|vs2|vs1|000 2+|vd|1010111|VDIV.VV 2+|11001|vm|vs2|vs1|100 2+|vd|1010111|VDIV.VS 2+|11001|vm|imm[4:0]|vs1|101 2+|vd|1010111|VDIV.VI 2+|11001|vm|vs2|vs1|010 2+|vd|1010111|VDIVU.VV 2+|11001|vm|vs2|vs1|110 2+|vd|1010111|VDIVU.VS 2+|11001|vm|imm[4:0]|vs1|111 2+|vd|1010111|VDIVU.VI 2+|11010|vm|vs2|vs1|000 2+|vd|1010111|VREM.VV 2+|11010|vm|vs2|vs1|100 2+|vd|1010111|VREM.VS 2+|11010|vm|imm[4:0]|vs1|101 2+|vd|1010111|VREM.VI 2+|11010|vm|vs2|vs1|010 2+|vd|1010111|VREMU.VV 2+|11010|vm|vs2|vs1|110 2+|vd|1010111|VREMU.VS 2+|11010|vm|imm[4:0]|vs1|111 2+|vd|1010111|VREMU.VI 2+|11011|vm|00000|vs1|000 2+|vd|1010111|VSQRT.VV 2+|11011|vm|00000|vs1|100 2+|vd|1010111|VSQRT.VS 2+|11011|vm|00000|vs1|101 2+|vd|1010111|VSQRT.VI 2+|11011|vm|00001|vs1|000 2+|vd|1010111|VFCLASS.VV 2+|11011|vm|00001|vs1|100 2+|vd|1010111|VFCLASS.VS 2+|11011|vm|00001|vs1|101 2+|vd|1010111|VFCLASS.VI 2+|11100|vm|vs2|vs1|000 2+|vd|1010111|VFSGNJ.VV 2+|11100|vm|vs2|vs1|100 2+|vd|1010111|VFSGNJ.VS 2+|11100|vm|imm[4:0]|vs1|101 2+|vd|1010111|VFSGNJ.VI 2+|11100|vm|vs2|vs1|010 2+|vd|1010111|VFSGNJN.VV 2+|11100|vm|vs2|vs1|110 2+|vd|1010111|VFSGNJN.VS 2+|11100|vm|imm[4:0]|vs1|111 2+|vd|1010111|VFSGNJN.VI 2+|11101|vm|vs2|vs1|000 2+|vd|1010111|VFSGNJX.VV 2+|11101|vm|vs2|vs1|100 2+|vd|1010111|VFSGNJX.VS 2+|11101|vm|imm[4:0]|vs1|101 2+|vd|1010111|VFSGNJX.VI 2+|11110|vm|vs2|vs1|000 2+|vd|1010111|VFMIN.VV 2+|11110|vm|vs2|vs1|100 2+|vd|1010111|VFMIN.VS 2+|11110|vm|imm[4:0]|vs1|101 2+|vd|1010111|VFMIN.VI 2+|11110|vm|vs2|vs1|010 2+|vd|1010111|VFMAX.VV 2+|11110|vm|vs2|vs1|110 2+|vd|1010111|VFMAX.VS 2+|11110|vm|imm[4:0]|vs1|111 2+|vd|1010111|VFMAX.VI |======================== .Vector Table [width=""100%"",cols=""^3,^3,^3,^4,^4,^3,^3,^3,^7,<10""] |======================== |31 30 |29 27 |26 25 |24 20 |19 15 |14 12 |11 10 |9 7 |6 0 |Opcode 2+|11011|vm|00000|vs1|010 2+|rd|1010111|VMPOPC 2+|11011|vm|00001|vs1|010 2+|rd|1010111|VMFIRST 2+|11011|vm|00000|vs1|011 2+|vd|1010111|VMSBF.V 2+|11011|vm|00001|vs1|011 2+|vd|1010111|VMSIF.V 2+|11011|vm|00010|vs1|011 2+|vd|1010111|VMSOF.V 2+|11011|vm|11111|00000|000 2+|vd|1010111|VIOTA.V 2+|11111|vm|vs2|vs1|000 2+|vd|1010111|VMERGE.VV 2+|11111|vm|vs2|vs1|100 2+|vd|1010111|VMERGE.VS 2+|11111|vm|imm[4:0]|vs1|101 2+|vd|1010111|VMERGE.VI 2+|01101|00|rs2|vs1|000 2+|rd|1010111|VMV.X.V 2+|01101|01|rs2|rs1|000 2+|vd|1010111|VMV.V.X 2+|01101|10|rs2|vs1|000 2+|vd|1010111|VMV.S.V 2+|01101|11|rs2|vs1|000 2+|vd|1010111|VMV.V.S 2+|01101|vm|vs2|vs1|011 2+|vd|1010111|VRGATHER.VV 2+|01101|vm|vs2|vs1|100 2+|vd|1010111|VSLIDEUP.VS 2+|01101|vm|imm[4:0]|00000|101 2+|vd|1010111|VSLIDEUP.VI 2+|01101|vm|vs2|vs1|110 2+|vd|1010111|VSLIDEDOWN.VS 2+|01101|vm|imm[4:0]|vs1|111 2+|vd|1010111|VSLIDEDOWN.VI 2+|01110|vm|vs2|vs1|000 2+|vd|1010111|VREDSUM.V 2+|01110|vm|vs2|vs1|010 2+|vd|1010111|VREDSUMW.V 2+|01110|vm|vs2|vs1|001 2+|vd|1010111|VREDMAX.V 2+|01110|vm|vs2|vs1|011 2+|vd|1010111|VREDMAXU.V 2+|01110|vm|vs2|vs1|100 2+|vd|1010111|VREDMIN.V 2+|01110|vm|vs2|vs1|110 2+|vd|1010111|VREDMINU.V 2+|01111|vm|vs2|vs1|000 2+|vd|1010111|VREDAND.V 2+|01111|vm|vs2|vs1|001 2+|vd|1010111|VREDOR.V 2+|01111|vm|vs2|vs1|010 2+|vd|1010111|VREDXOR.V 2+|vs3|vm|vs2|vs1|101 2+|vd|1000011|VMADD.VVV 2+|vs3|vm|vs2|vs1|110 2+|vd|1000011|VMADD.VVS 2+|vs3|vm|vs2|vs1|101 2+|vd|1000111|VMSUB.VVV 2+|vs3|vm|vs2|vs1|110 2+|vd|1000111|VMSUB.VVS 2+|vs3|vm|vs2|vs1|101 2+|vd|1001011|VMADDW.VVV 2+|vs3|vm|vs2|vs1|110 2+|vd|1001011|VMADDW.VVS 2+|vs3|vm|vs2|vs1|101 2+|vd|1001111|VMSUBW.VVV 2+|vs3|vm|vs2|vs1|110 2+|vd|1001111|VMSUBW.VVS |======================== //// ",12122,True,2962.4384085451757,median "// Copyright (c) 2014 The Bitcoin Core developers // Copyright (c) 2019 The quirkyturtcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include ""crypto/aes.h"" #include ""crypto/rfc6979_hmac_sha256.h"" #include ""crypto/chacha20.h"" #include ""crypto/ripemd160.h"" #include ""crypto/sha1.h"" #include ""crypto/sha256.h"" #include ""crypto/sha512.h"" #include ""crypto/hmac_sha256.h"" #include ""crypto/hmac_sha512.h"" #include ""random.h"" #include ""utilstrencodings.h"" #include ""test/test_quirkyturtcoin.h"" #include #include BOOST_FIXTURE_TEST_SUITE(crypto_tests, BasicTestingSetup) template void TestVector(const Hasher &h, const In &in, const Out &out) { Out hash; BOOST_CHECK(out.size() == h.OUTPUT_SIZE); hash.resize(out.size()); { // Test that writing the whole input string at once works. Hasher(h).Write((unsigned char*)&in[0], in.size()).Finalize(&hash[0]); BOOST_CHECK(hash == out); } for (int i=0; i<32; i++) { // Test that writing the string broken up in random pieces works. Hasher hasher(h); size_t pos = 0; while (pos < in.size()) { size_t len = InsecureRandRange((in.size() - pos + 1) / 2 + 1); hasher.Write((unsigned char*)&in[pos], len); pos += len; if (pos > 0 && pos + 2 * out.size() > in.size() && pos < in.size()) { // Test that writing the rest at once to a copy of a hasher works. Hasher(hasher).Write((unsigned char*)&in[pos], in.size() - pos).Finalize(&hash[0]); BOOST_CHECK(hash == out); } } hasher.Finalize(&hash[0]); BOOST_CHECK(hash == out); } } void TestSHA1(const std::string &in, const std::string &hexout) { TestVector(CSHA1(), in, ParseHex(hexout));} void TestSHA256(const std::string &in, const std::string &hexout) { TestVector(CSHA256(), in, ParseHex(hexout));} void TestSHA512(const std::string &in, const std::string &hexout) { TestVector(CSHA512(), in, ParseHex(hexout));} void TestRIPEMD160(const std::string &in, const std::string &hexout) { TestVector(CRIPEMD160(), in, ParseHex(hexout));} void TestHMACSHA256(const std::string &hexkey, const std::string &hexin, const std::string &hexout) { std::vector key = ParseHex(hexkey); TestVector(CHMAC_SHA256(&key[0], key.size()), ParseHex(hexin), ParseHex(hexout)); } void TestHMACSHA512(const std::string &hexkey, const std::string &hexin, const std::string &hexout) { std::vector key = ParseHex(hexkey); TestVector(CHMAC_SHA512(&key[0], key.size()), ParseHex(hexin), ParseHex(hexout)); } void TestChaCha20(const std::string &hex_message, const std::string &hexkey, uint64_t nonce, uint64_t seek, const std::string& hexout) { std::vector key = ParseHex(hexkey); std::vector m = ParseHex(hex_message); ChaCha20 rng(key.data(), key.size()); rng.SetIV(nonce); rng.Seek(seek); std::vector out = ParseHex(hexout); std::vector outres; outres.resize(out.size()); assert(hex_message.empty() || m.size() == out.size()); // perform the ChaCha20 round(s), if message is provided it will output the encrypted ciphertext otherwise the keystream if (!hex_message.empty()) { rng.Crypt(m.data(), outres.data(), outres.size()); } else { rng.Keystream(outres.data(), outres.size()); } BOOST_CHECK(out == outres); if (!hex_message.empty()) { // Manually XOR with the keystream and compare the output rng.SetIV(nonce); rng.Seek(seek); std::vector only_keystream(outres.size()); rng.Keystream(only_keystream.data(), only_keystream.size()); for (size_t i = 0; i != m.size(); i++) { outres[i] = m[i] ^ only_keystream[i]; } BOOST_CHECK(out == outres); } } void TestAES128(const std::string &hexkey, const std::string &hexin, const std::string &hexout) { std::vector key = ParseHex(hexkey); std::vector in = ParseHex(hexin); std::vector correctout = ParseHex(hexout); std::vector buf, buf2; assert(key.size() == 16); assert(in.size() == 16); assert(correctout.size() == 16); AES128Encrypt enc(&key[0]); buf.resize(correctout.size()); buf2.resize(correctout.size()); enc.Encrypt(&buf[0], &in[0]); BOOST_CHECK_EQUAL(HexStr(buf), HexStr(correctout)); AES128Decrypt dec(&key[0]); dec.Decrypt(&buf2[0], &buf[0]); BOOST_CHECK_EQUAL(HexStr(buf2), HexStr(in)); } void TestAES256(const std::string &hexkey, const std::string &hexin, const std::string &hexout) { std::vector key = ParseHex(hexkey); std::vector in = ParseHex(hexin); std::vector correctout = ParseHex(hexout); std::vector buf; assert(key.size() == 32); assert(in.size() == 16); assert(correctout.size() == 16); AES256Encrypt enc(&key[0]); buf.resize(correctout.size()); enc.Encrypt(&buf[0], &in[0]); BOOST_CHECK(buf == correctout); AES256Decrypt dec(&key[0]); dec.Decrypt(&buf[0], &buf[0]); BOOST_CHECK(buf == in); } void TestAES128CBC(const std::string &hexkey, const std::string &hexiv, bool pad, const std::string &hexin, const std::string &hexout) { std::vector key = ParseHex(hexkey); std::vector iv = ParseHex(hexiv); std::vector in = ParseHex(hexin); std::vector correctout = ParseHex(hexout); std::vector realout(in.size() + AES_BLOCKSIZE); // Encrypt the plaintext and verify that it equals the cipher AES128CBCEncrypt enc(&key[0], &iv[0], pad); int size = enc.Encrypt(&in[0], in.size(), &realout[0]); realout.resize(size); BOOST_CHECK(realout.size() == correctout.size()); BOOST_CHECK_MESSAGE(realout == correctout, HexStr(realout) + std::string("" != "") + hexout); // Decrypt the cipher and verify that it equals the plaintext std::vector decrypted(correctout.size()); AES128CBCDecrypt dec(&key[0], &iv[0], pad); size = dec.Decrypt(&correctout[0], correctout.size(), &decrypted[0]); decrypted.resize(size); BOOST_CHECK(decrypted.size() == in.size()); BOOST_CHECK_MESSAGE(decrypted == in, HexStr(decrypted) + std::string("" != "") + hexin); // Encrypt and re-decrypt substrings of the plaintext and verify that they equal each-other for(std::vector::iterator i(in.begin()); i != in.end(); ++i) { std::vector sub(i, in.end()); std::vector subout(sub.size() + AES_BLOCKSIZE); int size = enc.Encrypt(&sub[0], sub.size(), &subout[0]); if (size != 0) { subout.resize(size); std::vector subdecrypted(subout.size()); size = dec.Decrypt(&subout[0], subout.size(), &subdecrypted[0]); subdecrypted.resize(size); BOOST_CHECK(decrypted.size() == in.size()); BOOST_CHECK_MESSAGE(subdecrypted == sub, HexStr(subdecrypted) + std::string("" != "") + HexStr(sub)); } } } void TestAES256CBC(const std::string &hexkey, const std::string &hexiv, bool pad, const std::string &hexin, const std::string &hexout) { std::vector key = ParseHex(hexkey); std::vector iv = ParseHex(hexiv); std::vector in = ParseHex(hexin); std::vector correctout = ParseHex(hexout); std::vector realout(in.size() + AES_BLOCKSIZE); // Encrypt the plaintext and verify that it equals the cipher AES256CBCEncrypt enc(&key[0], &iv[0], pad); int size = enc.Encrypt(&in[0], in.size(), &realout[0]); realout.resize(size); BOOST_CHECK(realout.size() == correctout.size()); BOOST_CHECK_MESSAGE(realout == correctout, HexStr(realout) + std::string("" != "") + hexout); // Decrypt the cipher and verify that it equals the plaintext std::vector decrypted(correctout.size()); AES256CBCDecrypt dec(&key[0], &iv[0], pad); size = dec.Decrypt(&correctout[0], correctout.size(), &decrypted[0]); decrypted.resize(size); BOOST_CHECK(decrypted.size() == in.size()); BOOST_CHECK_MESSAGE(decrypted == in, HexStr(decrypted) + std::string("" != "") + hexin); // Encrypt and re-decrypt substrings of the plaintext and verify that they equal each-other for(std::vector::iterator i(in.begin()); i != in.end(); ++i) { std::vector sub(i, in.end()); std::vector subout(sub.size() + AES_BLOCKSIZE); int size = enc.Encrypt(&sub[0], sub.size(), &subout[0]); if (size != 0) { subout.resize(size); std::vector subdecrypted(subout.size()); size = dec.Decrypt(&subout[0], subout.size(), &subdecrypted[0]); subdecrypted.resize(size); BOOST_CHECK(decrypted.size() == in.size()); BOOST_CHECK_MESSAGE(subdecrypted == sub, HexStr(subdecrypted) + std::string("" != "") + HexStr(sub)); } } } std::string LongTestString(void) { std::string ret; for (int i=0; i<200000; i++) { ret += (unsigned char)(i); ret += (unsigned char)(i >> 4); ret += (unsigned char)(i >> 8); ret += (unsigned char)(i >> 12); ret += (unsigned char)(i >> 16); } return ret; } const std::string test1 = LongTestString(); BOOST_AUTO_TEST_CASE(ripemd160_testvectors) { TestRIPEMD160("""", ""9c1185a5c5e9fc54612808977ee8f548b2258d31""); TestRIPEMD160(""abc"", ""8eb208f7e05d987a9b044a8e98c6b087f15a0bfc""); TestRIPEMD160(""message digest"", ""5d0689ef49d2fae572b881b123a85ffa21595f36""); TestRIPEMD160(""secure hash algorithm"", ""20397528223b6a5f4cbc2808aba0464e645544f9""); TestRIPEMD160(""RIPEMD160 is considered to be safe"", ""a7d78608c7af8a8e728778e81576870734122b66""); TestRIPEMD160(""abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"", ""12a053384a9c0c88e405a06c27dcf49ada62eb2b""); TestRIPEMD160(""For this sample, this 63-byte string will be used as input data"", ""de90dbfee14b63fb5abf27c2ad4a82aaa5f27a11""); TestRIPEMD160(""This is exactly 64 bytes long, not counting the terminating byte"", ""eda31d51d3a623b81e19eb02e24ff65d27d67b37""); TestRIPEMD160(std::string(1000000, 'a'), ""52783243c1697bdbe16d37f97f68f08325dc1528""); TestRIPEMD160(test1, ""464243587bd146ea835cdf57bdae582f25ec45f1""); } BOOST_AUTO_TEST_CASE(sha1_testvectors) { TestSHA1("""", ""da39a3ee5e6b4b0d3255bfef95601890afd80709""); TestSHA1(""abc"", ""a9993e364706816aba3e25717850c26c9cd0d89d""); TestSHA1(""message digest"", ""c12252ceda8be8994d5fa0290a47231c1d16aae3""); TestSHA1(""secure hash algorithm"", ""d4d6d2f0ebe317513bbd8d967d89bac5819c2f60""); TestSHA1(""SHA1 is considered to be safe"", ""f2b6650569ad3a8720348dd6ea6c497dee3a842a""); TestSHA1(""abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"", ""84983e441c3bd26ebaae4aa1f95129e5e54670f1""); TestSHA1(""For this sample, this 63-byte string will be used as input data"", ""4f0ea5cd0585a23d028abdc1a6684e5a8094dc49""); TestSHA1(""This is exactly 64 bytes long, not counting the terminating byte"", ""fb679f23e7d1ce053313e66e127ab1b444397057""); TestSHA1(std::string(1000000, 'a'), ""34aa973cd4c4daa4f61eeb2bdbad27316534016f""); TestSHA1(test1, ""b7755760681cbfd971451668f32af5774f4656b5""); } BOOST_AUTO_TEST_CASE(sha256_testvectors) { TestSHA256("""", ""e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855""); TestSHA256(""abc"", ""ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad""); TestSHA256(""message digest"", ""f7846f55cf23e14eebeab5b4e1550cad5b509e3348fbc4efa3a1413d393cb650""); TestSHA256(""secure hash algorithm"", ""f30ceb2bb2829e79e4ca9753d35a8ecc00262d164cc077080295381cbd643f0d""); TestSHA256(""SHA256 is considered to be safe"", ""6819d915c73f4d1e77e4e1b52d1fa0f9cf9beaead3939f15874bd988e2a23630""); TestSHA256(""abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"", ""248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1""); TestSHA256(""For this sample, this 63-byte string will be used as input data"", ""f08a78cbbaee082b052ae0708f32fa1e50c5c421aa772ba5dbb406a2ea6be342""); TestSHA256(""This is exactly 64 bytes long, not counting the terminating byte"", ""ab64eff7e88e2e46165e29f2bce41826bd4c7b3552f6b382a9e7d3af47c245f8""); TestSHA256(""As Bitcoin relies on 80 byte header hashes, we want to have an example for that."", ""7406e8de7d6e4fffc573daef05aefb8806e7790f55eab5576f31349743cca743""); TestSHA256(std::string(1000000, 'a'), ""cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0""); TestSHA256(test1, ""a316d55510b49662420f49d145d42fb83f31ef8dc016aa4e32df049991a91e26""); } BOOST_AUTO_TEST_CASE(sha512_testvectors) { TestSHA512("""", ""cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"" ""47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e""); TestSHA512(""abc"", ""ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a"" ""2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f""); TestSHA512(""message digest"", ""107dbf389d9e9f71a3a95f6c055b9251bc5268c2be16d6c13492ea45b0199f33"" ""09e16455ab1e96118e8a905d5597b72038ddb372a89826046de66687bb420e7c""); TestSHA512(""secure hash algorithm"", ""7746d91f3de30c68cec0dd693120a7e8b04d8073cb699bdce1a3f64127bca7a3"" ""d5db502e814bb63c063a7a5043b2df87c61133395f4ad1edca7fcf4b30c3236e""); TestSHA512(""SHA512 is considered to be safe"", ""099e6468d889e1c79092a89ae925a9499b5408e01b66cb5b0a3bd0dfa51a9964"" ""6b4a3901caab1318189f74cd8cf2e941829012f2449df52067d3dd5b978456c2""); TestSHA512(""abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"", ""204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c335"" ""96fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445""); TestSHA512(""For this sample, this 63-byte string will be used as input data"", ""b3de4afbc516d2478fe9b518d063bda6c8dd65fc38402dd81d1eb7364e72fb6e"" ""6663cf6d2771c8f5a6da09601712fb3d2a36c6ffea3e28b0818b05b0a8660766""); TestSHA512(""This is exactly 64 bytes long, not counting the terminating byte"", ""70aefeaa0e7ac4f8fe17532d7185a289bee3b428d950c14fa8b713ca09814a38"" ""7d245870e007a80ad97c369d193e41701aa07f3221d15f0e65a1ff970cedf030""); TestSHA512(""abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno"" ""ijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"", ""8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018"" ""501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909""); TestSHA512(std::string(1000000, 'a'), ""e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb"" ""de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b""); TestSHA512(test1, ""40cac46c147e6131c5193dd5f34e9d8bb4951395f27b08c558c65ff4ba2de594"" ""37de8c3ef5459d76a52cedc02dc499a3c9ed9dedbfb3281afd9653b8a112fafc""); } BOOST_AUTO_TEST_CASE(hmac_sha256_testvectors) { // test cases 1, 2, 3, 4, 6 and 7 of RFC 4231 TestHMACSHA256(""0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"", ""4869205468657265"", ""b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7""); TestHMACSHA256(""4a656665"", ""7768617420646f2079612077616e7420666f72206e6f7468696e673f"", ""5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843""); TestHMACSHA256(""aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"", ""dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"" ""dddddddddddddddddddddddddddddddddddd"", ""773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe""); TestHMACSHA256(""0102030405060708090a0b0c0d0e0f10111213141516171819"", ""cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd"" ""cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd"", ""82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b""); TestHMACSHA256(""aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"" ""aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"" ""aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"" ""aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"" ""aaaaaa"", ""54657374205573696e67204c6172676572205468616e20426c6f636b2d53697a"" ""65204b6579202d2048617368204b6579204669727374"", ""60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54""); TestHMACSHA256(""aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"" ""aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"" ""aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"" ""aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"" ""aaaaaa"", ""5468697320697320612074657374207573696e672061206c6172676572207468"" ""616e20626c6f636b2d73697a65206b657920616e642061206c61726765722074"" ""68616e20626c6f636b2d73697a6520646174612e20546865206b6579206e6565"" ""647320746f20626520686173686564206265666f7265206265696e6720757365"" ""642062792074686520484d414320616c676f726974686d2e"", ""9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2""); } BOOST_AUTO_TEST_CASE(hmac_sha512_testvectors) { // test cases 1, 2, 3, 4, 6 and 7 of RFC 4231 TestHMACSHA512(""0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"", ""4869205468657265"", ""87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cde"" ""daa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854""); TestHMACSHA512(""4a656665"", ""7768617420646f2079612077616e7420666f72206e6f7468696e673f"", ""164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea250554"" ""9758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737""); TestHMACSHA512(""aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"", ""dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"" ""dddddddddddddddddddddddddddddddddddd"", ""fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33b2279d39"" ""bf3e848279a722c806b485a47e67c807b946a337bee8942674278859e13292fb""); TestHMACSHA512(""0102030405060708090a0b0c0d0e0f10111213141516171819"", ""cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd"" ""cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd"", ""b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050361ee3db"" ""a91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2de2adebeb10a298dd""); TestHMACSHA512(""aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"" ""aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"" ""aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"" ""aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"" ""aaaaaa"", ""54657374205573696e67204c6172676572205468616e20426c6f636b2d53697a"" ""65204b6579202d2048617368204b6579204669727374"", ""80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b013783f8f352"" ""6b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec8b915a985d786598""); TestHMACSHA512(""aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"" ""aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"" ""aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"" ""aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"" ""aaaaaa"", ""5468697320697320612074657374207573696e672061206c6172676572207468"" ""616e20626c6f636b2d73697a65206b657920616e642061206c61726765722074"" ""68616e20626c6f636b2d73697a6520646174612e20546865206b6579206e6565"" ""647320746f20626520686173686564206265666f7265206265696e6720757365"" ""642062792074686520484d414320616c676f726974686d2e"", ""e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d20cdc944"" ""b6022cac3c4982b10d5eeb55c3e4de15134676fb6de0446065c97440fa8c6a58""); } void TestRFC6979(const std::string& hexkey, const std::string& hexmsg, const std::vector& hexout) { std::vector key = ParseHex(hexkey); std::vector msg = ParseHex(hexmsg); RFC6979_HMAC_SHA256 rng(&key[0], key.size(), &msg[0], msg.size()); for (unsigned int i = 0; i < hexout.size(); i++) { std::vector out = ParseHex(hexout[i]); std::vector gen; gen.resize(out.size()); rng.Generate(&gen[0], gen.size()); BOOST_CHECK(out == gen); } } BOOST_AUTO_TEST_CASE(rfc6979_hmac_sha256) { TestRFC6979( ""0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f00"", ""4bf5122f344554c53bde2ebb8cd2b7e3d1600ad631c385a5d7cce23c7785459a"", {""4fe29525b2086809159acdf0506efb86b0ec932c7ba44256ab321e421e67e9fb"", ""2bf0fff1d3c378a22dc5de1d856522325c65b504491a0cbd01cb8f3aa67ffd4a"", ""f528b410cb541f77000d7afb6c5b53c5c471eab43e466d9ac5190c39c82fd82e""}); TestRFC6979( ""FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"", ""e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"", {""9c236c165b82ae0cd590659e100b6bab3036e7ba8b06749baf6981e16f1a2b95"", ""df471061625bc0ea14b682feee2c9c02f235da04204c1d62a1536c6e17aed7a9"", ""7597887cbd76321f32e30440679a22cf7f8d9d2eac390e581fea091ce202ba94""}); } BOOST_AUTO_TEST_CASE(chacha20_testvector) { // Test vector from RFC 7539 // test encryption TestChaCha20(""4c616469657320616e642047656e746c656d656e206f662074686520636c617373206f66202739393a204966204920636f756"" ""c64206f6666657220796f75206f6e6c79206f6e652074697020666f7220746865206675747572652c2073756e73637265656e"" ""20776f756c642062652069742e"", ""000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"", 0x4a000000UL, 1, ""6e2e359a2568f98041ba0728dd0d6981e97e7aec1d4360c20a27afccfd9fae0bf91b65c5524733ab8f593dabcd62b3571639d"" ""624e65152ab8f530c359f0861d807ca0dbf500d6a6156a38e088a22b65e52bc514d16ccf806818ce91ab77937365af90bbf74"" ""a35be6b40b8eedf2785e42874d"" ); // test keystream output TestChaCha20("""", ""000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"", 0x4a000000UL, 1, ""224f51f3401bd9e12fde276fb8631ded8c131f823d2c06e27e4fcaec9ef3cf788a3b0aa372600a92b57974cded2b9334794cb"" ""a40c63e34cdea212c4cf07d41b769a6749f3f630f4122cafe28ec4dc47e26d4346d70b98c73f3e9c53ac40c5945398b6eda1a"" ""832c89c167eacd901d7e2bf363""); // Test vectors from https://tools.ietf.org/html/draft-agl-tls-chacha20poly1305-04#section-7 TestChaCha20("""", ""0000000000000000000000000000000000000000000000000000000000000000"", 0, 0, ""76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7da41597c5157488d7724e03fb8d84a376a43b"" ""8f41518a11cc387b669b2ee6586""); TestChaCha20("""", ""0000000000000000000000000000000000000000000000000000000000000001"", 0, 0, ""4540f05a9f1fb296d7736e7b208e3c96eb4fe1834688d2604f450952ed432d41bbe2a0b6ea7566d2a5d1e7e20d42af2c53d79"" ""2b1c43fea817e9ad275ae546963""); TestChaCha20("""", ""0000000000000000000000000000000000000000000000000000000000000000"", 0x0100000000000000ULL, 0, ""de9cba7bf3d69ef5e786dc63973f653a0b49e015adbff7134fcb7df137821031e85a050278a7084527214f73efc7fa5b52770"" ""62eb7a0433e445f41e3""); TestChaCha20("""", ""0000000000000000000000000000000000000000000000000000000000000000"", 1, 0, ""ef3fdfd6c61578fbf5cf35bd3dd33b8009631634d21e42ac33960bd138e50d32111e4caf237ee53ca8ad6426194a88545ddc4"" ""97a0b466e7d6bbdb0041b2f586b""); TestChaCha20("""", ""000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"", 0x0706050403020100ULL, 0, ""f798a189f195e66982105ffb640bb7757f579da31602fc93ec01ac56f85ac3c134a4547b733b46413042c9440049176905d3b"" ""e59ea1c53f15916155c2be8241a38008b9a26bc35941e2444177c8ade6689de95264986d95889fb60e84629c9bd9a5acb1cc1"" ""18be563eb9b3a4a472f82e09a7e778492b562ef7130e88dfe031c79db9d4f7c7a899151b9a475032b63fc385245fe054e3dd5"" ""a97a5f576fe064025d3ce042c566ab2c507b138db853e3d6959660996546cc9c4a6eafdc777c040d70eaf46f76dad3979e5c5"" ""360c3317166a1c894c94a371876a94df7628fe4eaaf2ccb27d5aaae0ad7ad0f9d4b6ad3b54098746d4524d38407a6deb3ab78"" ""fab78c9""); } BOOST_AUTO_TEST_CASE(countbits_tests) { FastRandomContext ctx; for (int i = 0; i <= 64; ++i) { if (i == 0) { // Check handling of zero. BOOST_CHECK_EQUAL(CountBits(0), 0); } else if (i < 10) { for (uint64_t j = 1 << (i - 1); (j >> i) == 0; ++j) { // Exhaustively test up to 10 bits BOOST_CHECK_EQUAL(CountBits(j), i); } } else { for (int k = 0; k < 1000; k++) { // Randomly test 1000 samples of each length above 10 bits. uint64_t j = ((uint64_t)1) << (i - 1) | ctx.randbits(i - 1); BOOST_CHECK_EQUAL(CountBits(j), i); } } } } BOOST_AUTO_TEST_CASE(aes_testvectors) { // AES test vectors from FIPS 197. TestAES128(""000102030405060708090a0b0c0d0e0f"", ""00112233445566778899aabbccddeeff"", ""69c4e0d86a7b0430d8cdb78070b4c55a""); TestAES256(""000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"", ""00112233445566778899aabbccddeeff"", ""8ea2b7ca516745bfeafc49904b496089""); // AES-ECB test vectors from NIST sp800-38a. TestAES128(""2b7e151628aed2a6abf7158809cf4f3c"", ""6bc1bee22e409f96e93d7e117393172a"", ""3ad77bb40d7a3660a89ecaf32466ef97""); TestAES128(""2b7e151628aed2a6abf7158809cf4f3c"", ""ae2d8a571e03ac9c9eb76fac45af8e51"", ""f5d3d58503b9699de785895a96fdbaaf""); TestAES128(""2b7e151628aed2a6abf7158809cf4f3c"", ""30c81c46a35ce411e5fbc1191a0a52ef"", ""43b1cd7f598ece23881b00e3ed030688""); TestAES128(""2b7e151628aed2a6abf7158809cf4f3c"", ""f69f2445df4f9b17ad2b417be66c3710"", ""7b0c785e27e8ad3f8223207104725dd4""); TestAES256(""603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"", ""6bc1bee22e409f96e93d7e117393172a"", ""f3eed1bdb5d2a03c064b5a7e3db181f8""); TestAES256(""603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"", ""ae2d8a571e03ac9c9eb76fac45af8e51"", ""591ccb10d410ed26dc5ba74a31362870""); TestAES256(""603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"", ""30c81c46a35ce411e5fbc1191a0a52ef"", ""b6ed21b99ca6f4f9f153e7b1beafed1d""); TestAES256(""603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"", ""f69f2445df4f9b17ad2b417be66c3710"", ""23304b7a39f9f3ff067d8d8f9e24ecc7""); } BOOST_AUTO_TEST_CASE(aes_cbc_testvectors) { // NIST AES CBC 128-bit encryption test-vectors TestAES128CBC(""2b7e151628aed2a6abf7158809cf4f3c"", ""000102030405060708090A0B0C0D0E0F"", false, \\ ""6bc1bee22e409f96e93d7e117393172a"", ""7649abac8119b246cee98e9b12e9197d""); TestAES128CBC(""2b7e151628aed2a6abf7158809cf4f3c"", ""7649ABAC8119B246CEE98E9B12E9197D"", false, \\ ""ae2d8a571e03ac9c9eb76fac45af8e51"", ""5086cb9b507219ee95db113a917678b2""); TestAES128CBC(""2b7e151628aed2a6abf7158809cf4f3c"", ""5086cb9b507219ee95db113a917678b2"", false, \\ ""30c81c46a35ce411e5fbc1191a0a52ef"", ""73bed6b8e3c1743b7116e69e22229516""); TestAES128CBC(""2b7e151628aed2a6abf7158809cf4f3c"", ""73bed6b8e3c1743b7116e69e22229516"", false, \\ ""f69f2445df4f9b17ad2b417be66c3710"", ""3ff1caa1681fac09120eca307586e1a7""); // The same vectors with padding enabled TestAES128CBC(""2b7e151628aed2a6abf7158809cf4f3c"", ""000102030405060708090A0B0C0D0E0F"", true, \\ ""6bc1bee22e409f96e93d7e117393172a"", ""7649abac8119b246cee98e9b12e9197d8964e0b149c10b7b682e6e39aaeb731c""); TestAES128CBC(""2b7e151628aed2a6abf7158809cf4f3c"", ""7649ABAC8119B246CEE98E9B12E9197D"", true, \\ ""ae2d8a571e03ac9c9eb76fac45af8e51"", ""5086cb9b507219ee95db113a917678b255e21d7100b988ffec32feeafaf23538""); TestAES128CBC(""2b7e151628aed2a6abf7158809cf4f3c"", ""5086cb9b507219ee95db113a917678b2"", true, \\ ""30c81c46a35ce411e5fbc1191a0a52ef"", ""73bed6b8e3c1743b7116e69e22229516f6eccda327bf8e5ec43718b0039adceb""); TestAES128CBC(""2b7e151628aed2a6abf7158809cf4f3c"", ""73bed6b8e3c1743b7116e69e22229516"", true, \\ ""f69f2445df4f9b17ad2b417be66c3710"", ""3ff1caa1681fac09120eca307586e1a78cb82807230e1321d3fae00d18cc2012""); // NIST AES CBC 256-bit encryption test-vectors TestAES256CBC(""603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"", \\ ""000102030405060708090A0B0C0D0E0F"", false, ""6bc1bee22e409f96e93d7e117393172a"", \\ ""f58c4c04d6e5f1ba779eabfb5f7bfbd6""); TestAES256CBC(""603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"", \\ ""F58C4C04D6E5F1BA779EABFB5F7BFBD6"", false, ""ae2d8a571e03ac9c9eb76fac45af8e51"", \\ ""9cfc4e967edb808d679f777bc6702c7d""); TestAES256CBC(""603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"", \\ ""9CFC4E967EDB808D679F777BC6702C7D"", false, ""30c81c46a35ce411e5fbc1191a0a52ef"", ""39f23369a9d9bacfa530e26304231461""); TestAES256CBC(""603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"", \\ ""39F23369A9D9BACFA530E26304231461"", false, ""f69f2445df4f9b17ad2b417be66c3710"", \\ ""b2eb05e2c39be9fcda6c19078c6a9d1b""); // The same vectors with padding enabled TestAES256CBC(""603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"", \\ ""000102030405060708090A0B0C0D0E0F"", true, ""6bc1bee22e409f96e93d7e117393172a"", \\ ""f58c4c04d6e5f1ba779eabfb5f7bfbd6485a5c81519cf378fa36d42b8547edc0""); TestAES256CBC(""603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"", \\ ""F58C4C04D6E5F1BA779EABFB5F7BFBD6"", true, ""ae2d8a571e03ac9c9eb76fac45af8e51"", \\ ""9cfc4e967edb808d679f777bc6702c7d3a3aa5e0213db1a9901f9036cf5102d2""); TestAES256CBC(""603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"", \\ ""9CFC4E967EDB808D679F777BC6702C7D"", true, ""30c81c46a35ce411e5fbc1191a0a52ef"", ""39f23369a9d9bacfa530e263042314612f8da707643c90a6f732b3de1d3f5cee""); TestAES256CBC(""603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"", \\ ""39F23369A9D9BACFA530E26304231461"", true, ""f69f2445df4f9b17ad2b417be66c3710"", \\ ""b2eb05e2c39be9fcda6c19078c6a9d1b3f461796d6b0d6b2e0c2a72b4d80e644""); } BOOST_AUTO_TEST_SUITE_END() ",16182,True,3087.206155315729,median "/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include ""btCollisionWorld.h"" #include ""btCollisionDispatcher.h"" #include ""BulletCollision/CollisionDispatch/btCollisionObject.h"" #include ""BulletCollision/CollisionShapes/btCollisionShape.h"" #include ""BulletCollision/CollisionShapes/btConvexShape.h"" #include ""BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h"" #include ""BulletCollision/CollisionShapes/btSphereShape.h"" //for raycasting #include ""BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h"" //for raycasting #include ""BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h"" //for raycasting #include ""BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h"" //for raycasting #include ""BulletCollision/NarrowPhaseCollision/btRaycastCallback.h"" #include ""BulletCollision/CollisionShapes/btCompoundShape.h"" #include ""BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.h"" #include ""BulletCollision/NarrowPhaseCollision/btGjkConvexCast.h"" #include ""BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.h"" #include ""BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h"" #include ""BulletCollision/BroadphaseCollision/btBroadphaseInterface.h"" #include ""BulletCollision/BroadphaseCollision/btDbvt.h"" #include ""LinearMath/btAabbUtil2.h"" #include ""LinearMath/btQuickprof.h"" #include ""LinearMath/btSerializer.h"" #include ""BulletCollision/CollisionShapes/btConvexPolyhedron.h"" #include ""BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h"" //#define DISABLE_DBVT_COMPOUNDSHAPE_RAYCAST_ACCELERATION //#define USE_BRUTEFORCE_RAYBROADPHASE 1 //RECALCULATE_AABB is slower, but benefit is that you don't need to call 'stepSimulation' or 'updateAabbs' before using a rayTest //#define RECALCULATE_AABB_RAYCAST 1 //When the user doesn't provide dispatcher or broadphase, create basic versions (and delete them in destructor) #include ""BulletCollision/CollisionDispatch/btCollisionDispatcher.h"" #include ""BulletCollision/BroadphaseCollision/btSimpleBroadphase.h"" #include ""BulletCollision/CollisionDispatch/btCollisionConfiguration.h"" ///for debug drawing //for debug rendering #include ""BulletCollision/CollisionShapes/btBoxShape.h"" #include ""BulletCollision/CollisionShapes/btCapsuleShape.h"" #include ""BulletCollision/CollisionShapes/btCompoundShape.h"" #include ""BulletCollision/CollisionShapes/btConeShape.h"" #include ""BulletCollision/CollisionShapes/btConvexTriangleMeshShape.h"" #include ""BulletCollision/CollisionShapes/btCylinderShape.h"" #include ""BulletCollision/CollisionShapes/btMultiSphereShape.h"" #include ""BulletCollision/CollisionShapes/btPolyhedralConvexShape.h"" #include ""BulletCollision/CollisionShapes/btSphereShape.h"" #include ""BulletCollision/CollisionShapes/btTriangleCallback.h"" #include ""BulletCollision/CollisionShapes/btTriangleMeshShape.h"" #include ""BulletCollision/CollisionShapes/btStaticPlaneShape.h"" btCollisionWorld::btCollisionWorld(btDispatcher* dispatcher, btBroadphaseInterface* pairCache, btCollisionConfiguration* collisionConfiguration) : m_dispatcher1(dispatcher), m_broadphasePairCache(pairCache), m_debugDrawer(0), m_forceUpdateAllAabbs(true) { } btCollisionWorld::~btCollisionWorld() { //clean up remaining objects int i; for (i = 0; i < m_collisionObjects.size(); i++) { btCollisionObject* collisionObject = m_collisionObjects[i]; btBroadphaseProxy* bp = collisionObject->getBroadphaseHandle(); if (bp) { // // only clear the cached algorithms // getBroadphase()->getOverlappingPairCache()->cleanProxyFromPairs(bp, m_dispatcher1); getBroadphase()->destroyProxy(bp, m_dispatcher1); collisionObject->setBroadphaseHandle(0); } } } void btCollisionWorld::refreshBroadphaseProxy(btCollisionObject* collisionObject) { if (collisionObject->getBroadphaseHandle()) { int collisionFilterGroup = collisionObject->getBroadphaseHandle()->m_collisionFilterGroup; int collisionFilterMask = collisionObject->getBroadphaseHandle()->m_collisionFilterMask; getBroadphase()->destroyProxy(collisionObject->getBroadphaseHandle(), getDispatcher()); //calculate new AABB btTransform trans = collisionObject->getWorldTransform(); btVector3 minAabb; btVector3 maxAabb; collisionObject->getCollisionShape()->getAabb(trans, minAabb, maxAabb); int type = collisionObject->getCollisionShape()->getShapeType(); collisionObject->setBroadphaseHandle(getBroadphase()->createProxy( minAabb, maxAabb, type, collisionObject, collisionFilterGroup, collisionFilterMask, m_dispatcher1)); } } void btCollisionWorld::addCollisionObject(btCollisionObject* collisionObject, int collisionFilterGroup, int collisionFilterMask) { btAssert(collisionObject); //check that the object isn't already added btAssert(m_collisionObjects.findLinearSearch(collisionObject) == m_collisionObjects.size()); btAssert(collisionObject->getWorldArrayIndex() == -1); // do not add the same object to more than one collision world collisionObject->setWorldArrayIndex(m_collisionObjects.size()); m_collisionObjects.push_back(collisionObject); //calculate new AABB btTransform trans = collisionObject->getWorldTransform(); btVector3 minAabb; btVector3 maxAabb; collisionObject->getCollisionShape()->getAabb(trans, minAabb, maxAabb); int type = collisionObject->getCollisionShape()->getShapeType(); collisionObject->setBroadphaseHandle(getBroadphase()->createProxy( minAabb, maxAabb, type, collisionObject, collisionFilterGroup, collisionFilterMask, m_dispatcher1)); } void btCollisionWorld::updateSingleAabb(btCollisionObject* colObj) { btVector3 minAabb, maxAabb; colObj->getCollisionShape()->getAabb(colObj->getWorldTransform(), minAabb, maxAabb); //need to increase the aabb for contact thresholds btVector3 contactThreshold(gContactBreakingThreshold, gContactBreakingThreshold, gContactBreakingThreshold); minAabb -= contactThreshold; maxAabb += contactThreshold; if (getDispatchInfo().m_useContinuous && colObj->getInternalType() == btCollisionObject::CO_RIGID_BODY && !colObj->isStaticOrKinematicObject()) { btVector3 minAabb2, maxAabb2; colObj->getCollisionShape()->getAabb(colObj->getInterpolationWorldTransform(), minAabb2, maxAabb2); minAabb2 -= contactThreshold; maxAabb2 += contactThreshold; minAabb.setMin(minAabb2); maxAabb.setMax(maxAabb2); } btBroadphaseInterface* bp = (btBroadphaseInterface*)m_broadphasePairCache; //moving objects should be moderately sized, probably something wrong if not if (colObj->isStaticObject() || ((maxAabb - minAabb).length2() < btScalar(1e12))) { bp->setAabb(colObj->getBroadphaseHandle(), minAabb, maxAabb, m_dispatcher1); } else { //something went wrong, investigate //this assert is unwanted in 3D modelers (danger of loosing work) colObj->setActivationState(DISABLE_SIMULATION); static bool reportMe = true; if (reportMe && m_debugDrawer) { reportMe = false; m_debugDrawer->reportErrorWarning(""Overflow in AABB, object removed from simulation""); m_debugDrawer->reportErrorWarning(""If you can reproduce this, please email bugs@continuousphysics.com\\n""); m_debugDrawer->reportErrorWarning(""Please include above information, your Platform, version of OS.\\n""); m_debugDrawer->reportErrorWarning(""Thanks.\\n""); } } } void btCollisionWorld::updateAabbs() { BT_PROFILE(""updateAabbs""); btTransform predictedTrans; for (int i = 0; i < m_collisionObjects.size(); i++) { btCollisionObject* colObj = m_collisionObjects[i]; btAssert(colObj->getWorldArrayIndex() == i); //only update aabb of active objects if (m_forceUpdateAllAabbs || colObj->isActive()) { updateSingleAabb(colObj); } } } void btCollisionWorld::computeOverlappingPairs() { BT_PROFILE(""calculateOverlappingPairs""); m_broadphasePairCache->calculateOverlappingPairs(m_dispatcher1); } void btCollisionWorld::performDiscreteCollisionDetection() { BT_PROFILE(""performDiscreteCollisionDetection""); btDispatcherInfo& dispatchInfo = getDispatchInfo(); updateAabbs(); computeOverlappingPairs(); btDispatcher* dispatcher = getDispatcher(); { BT_PROFILE(""dispatchAllCollisionPairs""); if (dispatcher) dispatcher->dispatchAllCollisionPairs(m_broadphasePairCache->getOverlappingPairCache(), dispatchInfo, m_dispatcher1); } } void btCollisionWorld::removeCollisionObject(btCollisionObject* collisionObject) { //bool removeFromBroadphase = false; { btBroadphaseProxy* bp = collisionObject->getBroadphaseHandle(); if (bp) { // // only clear the cached algorithms // getBroadphase()->getOverlappingPairCache()->cleanProxyFromPairs(bp, m_dispatcher1); getBroadphase()->destroyProxy(bp, m_dispatcher1); collisionObject->setBroadphaseHandle(0); } } int iObj = collisionObject->getWorldArrayIndex(); // btAssert(iObj >= 0 && iObj < m_collisionObjects.size()); // trying to remove an object that was never added or already removed previously? if (iObj >= 0 && iObj < m_collisionObjects.size()) { btAssert(collisionObject == m_collisionObjects[iObj]); m_collisionObjects.swap(iObj, m_collisionObjects.size() - 1); m_collisionObjects.pop_back(); if (iObj < m_collisionObjects.size()) { m_collisionObjects[iObj]->setWorldArrayIndex(iObj); } } else { // slow linear search //swapremove m_collisionObjects.remove(collisionObject); } collisionObject->setWorldArrayIndex(-1); } void btCollisionWorld::rayTestSingle(const btTransform& rayFromTrans, const btTransform& rayToTrans, btCollisionObject* collisionObject, const btCollisionShape* collisionShape, const btTransform& colObjWorldTransform, RayResultCallback& resultCallback) { btCollisionObjectWrapper colObWrap(0, collisionShape, collisionObject, colObjWorldTransform, -1, -1); btCollisionWorld::rayTestSingleInternal(rayFromTrans, rayToTrans, &colObWrap, resultCallback); } void btCollisionWorld::rayTestSingleInternal(const btTransform& rayFromTrans, const btTransform& rayToTrans, const btCollisionObjectWrapper* collisionObjectWrap, RayResultCallback& resultCallback) { btSphereShape pointShape(btScalar(0.0)); pointShape.setMargin(0.f); const btConvexShape* castShape = &pointShape; const btCollisionShape* collisionShape = collisionObjectWrap->getCollisionShape(); const btTransform& colObjWorldTransform = collisionObjectWrap->getWorldTransform(); if (collisionShape->isConvex()) { // BT_PROFILE(""rayTestConvex""); btConvexCast::CastResult castResult; castResult.m_fraction = resultCallback.m_closestHitFraction; btConvexShape* convexShape = (btConvexShape*)collisionShape; btVoronoiSimplexSolver simplexSolver; btSubsimplexConvexCast subSimplexConvexCaster(castShape, convexShape, &simplexSolver); btGjkConvexCast gjkConvexCaster(castShape, convexShape, &simplexSolver); //btContinuousConvexCollision convexCaster(castShape,convexShape,&simplexSolver,0); btConvexCast* convexCasterPtr = 0; //use kF_UseSubSimplexConvexCastRaytest by default if (resultCallback.m_flags & btTriangleRaycastCallback::kF_UseGjkConvexCastRaytest) convexCasterPtr = &gjkConvexCaster; else convexCasterPtr = &subSimplexConvexCaster; btConvexCast& convexCaster = *convexCasterPtr; if (convexCaster.calcTimeOfImpact(rayFromTrans, rayToTrans, colObjWorldTransform, colObjWorldTransform, castResult)) { //add hit if (castResult.m_normal.length2() > btScalar(0.0001)) { if (castResult.m_fraction < resultCallback.m_closestHitFraction) { //todo: figure out what this is about. When is rayFromTest.getBasis() not identity? #ifdef USE_SUBSIMPLEX_CONVEX_CAST //rotate normal into worldspace castResult.m_normal = rayFromTrans.getBasis() * castResult.m_normal; #endif //USE_SUBSIMPLEX_CONVEX_CAST castResult.m_normal.normalize(); btCollisionWorld::LocalRayResult localRayResult( collisionObjectWrap->getCollisionObject(), 0, castResult.m_normal, castResult.m_fraction); bool normalInWorldSpace = true; resultCallback.addSingleResult(localRayResult, normalInWorldSpace); } } } } else { if (collisionShape->isConcave()) { //ConvexCast::CastResult struct BridgeTriangleRaycastCallback : public btTriangleRaycastCallback { btCollisionWorld::RayResultCallback* m_resultCallback; const btCollisionObject* m_collisionObject; const btConcaveShape* m_triangleMesh; btTransform m_colObjWorldTransform; BridgeTriangleRaycastCallback(const btVector3& from, const btVector3& to, btCollisionWorld::RayResultCallback* resultCallback, const btCollisionObject* collisionObject, const btConcaveShape* triangleMesh, const btTransform& colObjWorldTransform) : //@BP Mod btTriangleRaycastCallback(from, to, resultCallback->m_flags), m_resultCallback(resultCallback), m_collisionObject(collisionObject), m_triangleMesh(triangleMesh), m_colObjWorldTransform(colObjWorldTransform) { } virtual btScalar reportHit(const btVector3& hitNormalLocal, btScalar hitFraction, int partId, int triangleIndex) { btCollisionWorld::LocalShapeInfo shapeInfo; shapeInfo.m_shapePart = partId; shapeInfo.m_triangleIndex = triangleIndex; btVector3 hitNormalWorld = m_colObjWorldTransform.getBasis() * hitNormalLocal; btCollisionWorld::LocalRayResult rayResult(m_collisionObject, &shapeInfo, hitNormalWorld, hitFraction); bool normalInWorldSpace = true; return m_resultCallback->addSingleResult(rayResult, normalInWorldSpace); } }; btTransform worldTocollisionObject = colObjWorldTransform.inverse(); btVector3 rayFromLocal = worldTocollisionObject * rayFromTrans.getOrigin(); btVector3 rayToLocal = worldTocollisionObject * rayToTrans.getOrigin(); // BT_PROFILE(""rayTestConcave""); if (collisionShape->getShapeType() == TRIANGLE_MESH_SHAPE_PROXYTYPE) { ///optimized version for btBvhTriangleMeshShape btBvhTriangleMeshShape* triangleMesh = (btBvhTriangleMeshShape*)collisionShape; BridgeTriangleRaycastCallback rcb(rayFromLocal, rayToLocal, &resultCallback, collisionObjectWrap->getCollisionObject(), triangleMesh, colObjWorldTransform); rcb.m_hitFraction = resultCallback.m_closestHitFraction; triangleMesh->performRaycast(&rcb, rayFromLocal, rayToLocal); } else if (collisionShape->getShapeType() == SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE) { ///optimized version for btScaledBvhTriangleMeshShape btScaledBvhTriangleMeshShape* scaledTriangleMesh = (btScaledBvhTriangleMeshShape*)collisionShape; btBvhTriangleMeshShape* triangleMesh = (btBvhTriangleMeshShape*)scaledTriangleMesh->getChildShape(); //scale the ray positions btVector3 scale = scaledTriangleMesh->getLocalScaling(); btVector3 rayFromLocalScaled = rayFromLocal / scale; btVector3 rayToLocalScaled = rayToLocal / scale; //perform raycast in the underlying btBvhTriangleMeshShape BridgeTriangleRaycastCallback rcb(rayFromLocalScaled, rayToLocalScaled, &resultCallback, collisionObjectWrap->getCollisionObject(), triangleMesh, colObjWorldTransform); rcb.m_hitFraction = resultCallback.m_closestHitFraction; triangleMesh->performRaycast(&rcb, rayFromLocalScaled, rayToLocalScaled); } else if (((resultCallback.m_flags&btTriangleRaycastCallback::kF_DisableHeightfieldAccelerator)==0) && collisionShape->getShapeType() == TERRAIN_SHAPE_PROXYTYPE ) { ///optimized version for btHeightfieldTerrainShape btHeightfieldTerrainShape* heightField = (btHeightfieldTerrainShape*)collisionShape; btTransform worldTocollisionObject = colObjWorldTransform.inverse(); btVector3 rayFromLocal = worldTocollisionObject * rayFromTrans.getOrigin(); btVector3 rayToLocal = worldTocollisionObject * rayToTrans.getOrigin(); BridgeTriangleRaycastCallback rcb(rayFromLocal, rayToLocal, &resultCallback, collisionObjectWrap->getCollisionObject(), heightField, colObjWorldTransform); rcb.m_hitFraction = resultCallback.m_closestHitFraction; heightField->performRaycast(&rcb, rayFromLocal, rayToLocal); } else { //generic (slower) case btConcaveShape* concaveShape = (btConcaveShape*)collisionShape; btTransform worldTocollisionObject = colObjWorldTransform.inverse(); btVector3 rayFromLocal = worldTocollisionObject * rayFromTrans.getOrigin(); btVector3 rayToLocal = worldTocollisionObject * rayToTrans.getOrigin(); //ConvexCast::CastResult struct BridgeTriangleRaycastCallback : public btTriangleRaycastCallback { btCollisionWorld::RayResultCallback* m_resultCallback; const btCollisionObject* m_collisionObject; btConcaveShape* m_triangleMesh; btTransform m_colObjWorldTransform; BridgeTriangleRaycastCallback(const btVector3& from, const btVector3& to, btCollisionWorld::RayResultCallback* resultCallback, const btCollisionObject* collisionObject, btConcaveShape* triangleMesh, const btTransform& colObjWorldTransform) : //@BP Mod btTriangleRaycastCallback(from, to, resultCallback->m_flags), m_resultCallback(resultCallback), m_collisionObject(collisionObject), m_triangleMesh(triangleMesh), m_colObjWorldTransform(colObjWorldTransform) { } virtual btScalar reportHit(const btVector3& hitNormalLocal, btScalar hitFraction, int partId, int triangleIndex) { btCollisionWorld::LocalShapeInfo shapeInfo; shapeInfo.m_shapePart = partId; shapeInfo.m_triangleIndex = triangleIndex; btVector3 hitNormalWorld = m_colObjWorldTransform.getBasis() * hitNormalLocal; btCollisionWorld::LocalRayResult rayResult(m_collisionObject, &shapeInfo, hitNormalWorld, hitFraction); bool normalInWorldSpace = true; return m_resultCallback->addSingleResult(rayResult, normalInWorldSpace); } }; BridgeTriangleRaycastCallback rcb(rayFromLocal, rayToLocal, &resultCallback, collisionObjectWrap->getCollisionObject(), concaveShape, colObjWorldTransform); rcb.m_hitFraction = resultCallback.m_closestHitFraction; btVector3 rayAabbMinLocal = rayFromLocal; rayAabbMinLocal.setMin(rayToLocal); btVector3 rayAabbMaxLocal = rayFromLocal; rayAabbMaxLocal.setMax(rayToLocal); concaveShape->processAllTriangles(&rcb, rayAabbMinLocal, rayAabbMaxLocal); } } else { // BT_PROFILE(""rayTestCompound""); if (collisionShape->isCompound()) { struct LocalInfoAdder2 : public RayResultCallback { RayResultCallback* m_userCallback; int m_i; LocalInfoAdder2(int i, RayResultCallback* user) : m_userCallback(user), m_i(i) { m_closestHitFraction = m_userCallback->m_closestHitFraction; m_flags = m_userCallback->m_flags; } virtual bool needsCollision(btBroadphaseProxy* p) const { return m_userCallback->needsCollision(p); } virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& r, bool b) { btCollisionWorld::LocalShapeInfo shapeInfo; shapeInfo.m_shapePart = -1; shapeInfo.m_triangleIndex = m_i; if (r.m_localShapeInfo == NULL) r.m_localShapeInfo = &shapeInfo; const btScalar result = m_userCallback->addSingleResult(r, b); m_closestHitFraction = m_userCallback->m_closestHitFraction; return result; } }; struct RayTester : btDbvt::ICollide { const btCollisionObject* m_collisionObject; const btCompoundShape* m_compoundShape; const btTransform& m_colObjWorldTransform; const btTransform& m_rayFromTrans; const btTransform& m_rayToTrans; RayResultCallback& m_resultCallback; RayTester(const btCollisionObject* collisionObject, const btCompoundShape* compoundShape, const btTransform& colObjWorldTransform, const btTransform& rayFromTrans, const btTransform& rayToTrans, RayResultCallback& resultCallback) : m_collisionObject(collisionObject), m_compoundShape(compoundShape), m_colObjWorldTransform(colObjWorldTransform), m_rayFromTrans(rayFromTrans), m_rayToTrans(rayToTrans), m_resultCallback(resultCallback) { } void ProcessLeaf(int i) { const btCollisionShape* childCollisionShape = m_compoundShape->getChildShape(i); const btTransform& childTrans = m_compoundShape->getChildTransform(i); btTransform childWorldTrans = m_colObjWorldTransform * childTrans; btCollisionObjectWrapper tmpOb(0, childCollisionShape, m_collisionObject, childWorldTrans, -1, i); // replace collision shape so that callback can determine the triangle LocalInfoAdder2 my_cb(i, &m_resultCallback); rayTestSingleInternal( m_rayFromTrans, m_rayToTrans, &tmpOb, my_cb); } void Process(const btDbvtNode* leaf) { ProcessLeaf(leaf->dataAsInt); } }; const btCompoundShape* compoundShape = static_cast(collisionShape); const btDbvt* dbvt = compoundShape->getDynamicAabbTree(); RayTester rayCB( collisionObjectWrap->getCollisionObject(), compoundShape, colObjWorldTransform, rayFromTrans, rayToTrans, resultCallback); #ifndef DISABLE_DBVT_COMPOUNDSHAPE_RAYCAST_ACCELERATION if (dbvt) { btVector3 localRayFrom = colObjWorldTransform.inverseTimes(rayFromTrans).getOrigin(); btVector3 localRayTo = colObjWorldTransform.inverseTimes(rayToTrans).getOrigin(); btDbvt::rayTest(dbvt->m_root, localRayFrom, localRayTo, rayCB); } else #endif //DISABLE_DBVT_COMPOUNDSHAPE_RAYCAST_ACCELERATION { for (int i = 0, n = compoundShape->getNumChildShapes(); i < n; ++i) { rayCB.ProcessLeaf(i); } } } } } } void btCollisionWorld::objectQuerySingle(const btConvexShape* castShape, const btTransform& convexFromTrans, const btTransform& convexToTrans, btCollisionObject* collisionObject, const btCollisionShape* collisionShape, const btTransform& colObjWorldTransform, ConvexResultCallback& resultCallback, btScalar allowedPenetration) { btCollisionObjectWrapper tmpOb(0, collisionShape, collisionObject, colObjWorldTransform, -1, -1); btCollisionWorld::objectQuerySingleInternal(castShape, convexFromTrans, convexToTrans, &tmpOb, resultCallback, allowedPenetration); } void btCollisionWorld::objectQuerySingleInternal(const btConvexShape* castShape, const btTransform& convexFromTrans, const btTransform& convexToTrans, const btCollisionObjectWrapper* colObjWrap, ConvexResultCallback& resultCallback, btScalar allowedPenetration) { const btCollisionShape* collisionShape = colObjWrap->getCollisionShape(); const btTransform& colObjWorldTransform = colObjWrap->getWorldTransform(); if (collisionShape->isConvex()) { //BT_PROFILE(""convexSweepConvex""); btConvexCast::CastResult castResult; castResult.m_allowedPenetration = allowedPenetration; castResult.m_fraction = resultCallback.m_closestHitFraction; //btScalar(1.);//?? btConvexShape* convexShape = (btConvexShape*)collisionShape; btVoronoiSimplexSolver simplexSolver; btGjkEpaPenetrationDepthSolver gjkEpaPenetrationSolver; btContinuousConvexCollision convexCaster1(castShape, convexShape, &simplexSolver, &gjkEpaPenetrationSolver); //btGjkConvexCast convexCaster2(castShape,convexShape,&simplexSolver); //btSubsimplexConvexCast convexCaster3(castShape,convexShape,&simplexSolver); btConvexCast* castPtr = &convexCaster1; if (castPtr->calcTimeOfImpact(convexFromTrans, convexToTrans, colObjWorldTransform, colObjWorldTransform, castResult)) { //add hit if (castResult.m_normal.length2() > btScalar(0.0001)) { if (castResult.m_fraction < resultCallback.m_closestHitFraction) { castResult.m_normal.normalize(); btCollisionWorld::LocalConvexResult localConvexResult( colObjWrap->getCollisionObject(), 0, castResult.m_normal, castResult.m_hitPoint, castResult.m_fraction); localConvexResult.m_penetrationDepth = castResult.m_penetrationDepth; bool normalInWorldSpace = true; resultCallback.addSingleResult(localConvexResult, normalInWorldSpace); } } } } else { if (collisionShape->isConcave()) { if (collisionShape->getShapeType() == TRIANGLE_MESH_SHAPE_PROXYTYPE) { //BT_PROFILE(""convexSweepbtBvhTriangleMesh""); btBvhTriangleMeshShape* triangleMesh = (btBvhTriangleMeshShape*)collisionShape; btTransform worldTocollisionObject = colObjWorldTransform.inverse(); btVector3 convexFromLocal = worldTocollisionObject * convexFromTrans.getOrigin(); btVector3 convexToLocal = worldTocollisionObject * convexToTrans.getOrigin(); // rotation of box in local mesh space = MeshRotation^-1 * ConvexToRotation btTransform rotationXform = btTransform(worldTocollisionObject.getBasis() * convexToTrans.getBasis()); //ConvexCast::CastResult struct BridgeTriangleConvexcastCallback : public btTriangleConvexcastCallback { btCollisionWorld::ConvexResultCallback* m_resultCallback; const btCollisionObject* m_collisionObject; btTriangleMeshShape* m_triangleMesh; BridgeTriangleConvexcastCallback(const btConvexShape* castShape, const btTransform& from, const btTransform& to, btCollisionWorld::ConvexResultCallback* resultCallback, const btCollisionObject* collisionObject, btTriangleMeshShape* triangleMesh, const btTransform& triangleToWorld) : btTriangleConvexcastCallback(castShape, from, to, triangleToWorld, triangleMesh->getMargin()), m_resultCallback(resultCallback), m_collisionObject(collisionObject), m_triangleMesh(triangleMesh) { } virtual btScalar reportHit(const btVector3& hitNormalLocal, const btVector3& hitPointLocal, btScalar hitFraction, int partId, int triangleIndex) { btCollisionWorld::LocalShapeInfo shapeInfo; shapeInfo.m_shapePart = partId; shapeInfo.m_triangleIndex = triangleIndex; if (hitFraction <= m_resultCallback->m_closestHitFraction) { btCollisionWorld::LocalConvexResult convexResult(m_collisionObject, &shapeInfo, hitNormalLocal, hitPointLocal, hitFraction); bool normalInWorldSpace = true; return m_resultCallback->addSingleResult(convexResult, normalInWorldSpace); } return hitFraction; } }; BridgeTriangleConvexcastCallback tccb(castShape, convexFromTrans, convexToTrans, &resultCallback, colObjWrap->getCollisionObject(), triangleMesh, colObjWorldTransform); tccb.m_hitFraction = resultCallback.m_closestHitFraction; tccb.m_allowedPenetration = allowedPenetration; btVector3 boxMinLocal, boxMaxLocal; castShape->getAabb(rotationXform, boxMinLocal, boxMaxLocal); triangleMesh->performConvexcast(&tccb, convexFromLocal, convexToLocal, boxMinLocal, boxMaxLocal); } else { if (collisionShape->getShapeType() == STATIC_PLANE_PROXYTYPE) { btConvexCast::CastResult castResult; castResult.m_allowedPenetration = allowedPenetration; castResult.m_fraction = resultCallback.m_closestHitFraction; btStaticPlaneShape* planeShape = (btStaticPlaneShape*)collisionShape; btContinuousConvexCollision convexCaster1(castShape, planeShape); btConvexCast* castPtr = &convexCaster1; if (castPtr->calcTimeOfImpact(convexFromTrans, convexToTrans, colObjWorldTransform, colObjWorldTransform, castResult)) { //add hit if (castResult.m_normal.length2() > btScalar(0.0001)) { if (castResult.m_fraction < resultCallback.m_closestHitFraction) { castResult.m_normal.normalize(); btCollisionWorld::LocalConvexResult localConvexResult( colObjWrap->getCollisionObject(), 0, castResult.m_normal, castResult.m_hitPoint, castResult.m_fraction); bool normalInWorldSpace = true; resultCallback.addSingleResult(localConvexResult, normalInWorldSpace); } } } } else { //BT_PROFILE(""convexSweepConcave""); btConcaveShape* concaveShape = (btConcaveShape*)collisionShape; btTransform worldTocollisionObject = colObjWorldTransform.inverse(); btVector3 convexFromLocal = worldTocollisionObject * convexFromTrans.getOrigin(); btVector3 convexToLocal = worldTocollisionObject * convexToTrans.getOrigin(); // rotation of box in local mesh space = MeshRotation^-1 * ConvexToRotation btTransform rotationXform = btTransform(worldTocollisionObject.getBasis() * convexToTrans.getBasis()); //ConvexCast::CastResult struct BridgeTriangleConvexcastCallback : public btTriangleConvexcastCallback { btCollisionWorld::ConvexResultCallback* m_resultCallback; const btCollisionObject* m_collisionObject; btConcaveShape* m_triangleMesh; BridgeTriangleConvexcastCallback(const btConvexShape* castShape, const btTransform& from, const btTransform& to, btCollisionWorld::ConvexResultCallback* resultCallback, const btCollisionObject* collisionObject, btConcaveShape* triangleMesh, const btTransform& triangleToWorld) : btTriangleConvexcastCallback(castShape, from, to, triangleToWorld, triangleMesh->getMargin()), m_resultCallback(resultCallback), m_collisionObject(collisionObject), m_triangleMesh(triangleMesh) { } virtual btScalar reportHit(const btVector3& hitNormalLocal, const btVector3& hitPointLocal, btScalar hitFraction, int partId, int triangleIndex) { btCollisionWorld::LocalShapeInfo shapeInfo; shapeInfo.m_shapePart = partId; shapeInfo.m_triangleIndex = triangleIndex; if (hitFraction <= m_resultCallback->m_closestHitFraction) { btCollisionWorld::LocalConvexResult convexResult(m_collisionObject, &shapeInfo, hitNormalLocal, hitPointLocal, hitFraction); bool normalInWorldSpace = true; return m_resultCallback->addSingleResult(convexResult, normalInWorldSpace); } return hitFraction; } }; BridgeTriangleConvexcastCallback tccb(castShape, convexFromTrans, convexToTrans, &resultCallback, colObjWrap->getCollisionObject(), concaveShape, colObjWorldTransform); tccb.m_hitFraction = resultCallback.m_closestHitFraction; tccb.m_allowedPenetration = allowedPenetration; btVector3 boxMinLocal, boxMaxLocal; castShape->getAabb(rotationXform, boxMinLocal, boxMaxLocal); btVector3 rayAabbMinLocal = convexFromLocal; rayAabbMinLocal.setMin(convexToLocal); btVector3 rayAabbMaxLocal = convexFromLocal; rayAabbMaxLocal.setMax(convexToLocal); rayAabbMinLocal += boxMinLocal; rayAabbMaxLocal += boxMaxLocal; concaveShape->processAllTriangles(&tccb, rayAabbMinLocal, rayAabbMaxLocal); } } } else { if (collisionShape->isCompound()) { struct btCompoundLeafCallback : btDbvt::ICollide { btCompoundLeafCallback( const btCollisionObjectWrapper* colObjWrap, const btConvexShape* castShape, const btTransform& convexFromTrans, const btTransform& convexToTrans, btScalar allowedPenetration, const btCompoundShape* compoundShape, const btTransform& colObjWorldTransform, ConvexResultCallback& resultCallback) : m_colObjWrap(colObjWrap), m_castShape(castShape), m_convexFromTrans(convexFromTrans), m_convexToTrans(convexToTrans), m_allowedPenetration(allowedPenetration), m_compoundShape(compoundShape), m_colObjWorldTransform(colObjWorldTransform), m_resultCallback(resultCallback) { } const btCollisionObjectWrapper* m_colObjWrap; const btConvexShape* m_castShape; const btTransform& m_convexFromTrans; const btTransform& m_convexToTrans; btScalar m_allowedPenetration; const btCompoundShape* m_compoundShape; const btTransform& m_colObjWorldTransform; ConvexResultCallback& m_resultCallback; public: void ProcessChild(int index, const btTransform& childTrans, const btCollisionShape* childCollisionShape) { btTransform childWorldTrans = m_colObjWorldTransform * childTrans; struct LocalInfoAdder : public ConvexResultCallback { ConvexResultCallback* m_userCallback; int m_i; LocalInfoAdder(int i, ConvexResultCallback* user) : m_userCallback(user), m_i(i) { m_closestHitFraction = m_userCallback->m_closestHitFraction; } virtual bool needsCollision(btBroadphaseProxy* p) const { return m_userCallback->needsCollision(p); } virtual btScalar addSingleResult(btCollisionWorld::LocalConvexResult& r, bool b) { btCollisionWorld::LocalShapeInfo shapeInfo; shapeInfo.m_shapePart = -1; shapeInfo.m_triangleIndex = m_i; if (r.m_localShapeInfo == NULL) r.m_localShapeInfo = &shapeInfo; const btScalar result = m_userCallback->addSingleResult(r, b); m_closestHitFraction = m_userCallback->m_closestHitFraction; return result; } }; LocalInfoAdder my_cb(index, &m_resultCallback); btCollisionObjectWrapper tmpObj(m_colObjWrap, childCollisionShape, m_colObjWrap->getCollisionObject(), childWorldTrans, -1, index); objectQuerySingleInternal(m_castShape, m_convexFromTrans, m_convexToTrans, &tmpObj, my_cb, m_allowedPenetration); } void Process(const btDbvtNode* leaf) { // Processing leaf node int index = leaf->dataAsInt; btTransform childTrans = m_compoundShape->getChildTransform(index); const btCollisionShape* childCollisionShape = m_compoundShape->getChildShape(index); ProcessChild(index, childTrans, childCollisionShape); } }; BT_PROFILE(""convexSweepCompound""); const btCompoundShape* compoundShape = static_cast(collisionShape); btVector3 fromLocalAabbMin, fromLocalAabbMax; btVector3 toLocalAabbMin, toLocalAabbMax; castShape->getAabb(colObjWorldTransform.inverse() * convexFromTrans, fromLocalAabbMin, fromLocalAabbMax); castShape->getAabb(colObjWorldTransform.inverse() * convexToTrans, toLocalAabbMin, toLocalAabbMax); fromLocalAabbMin.setMin(toLocalAabbMin); fromLocalAabbMax.setMax(toLocalAabbMax); btCompoundLeafCallback callback(colObjWrap, castShape, convexFromTrans, convexToTrans, allowedPenetration, compoundShape, colObjWorldTransform, resultCallback); const btDbvt* tree = compoundShape->getDynamicAabbTree(); if (tree) { const ATTRIBUTE_ALIGNED16(btDbvtVolume) bounds = btDbvtVolume::FromMM(fromLocalAabbMin, fromLocalAabbMax); tree->collideTV(tree->m_root, bounds, callback); } else { int i; for (i = 0; i < compoundShape->getNumChildShapes(); i++) { const btCollisionShape* childCollisionShape = compoundShape->getChildShape(i); btTransform childTrans = compoundShape->getChildTransform(i); callback.ProcessChild(i, childTrans, childCollisionShape); } } } } } } struct btSingleRayCallback : public btBroadphaseRayCallback { btVector3 m_rayFromWorld; btVector3 m_rayToWorld; btTransform m_rayFromTrans; btTransform m_rayToTrans; btVector3 m_hitNormal; const btCollisionWorld* m_world; btCollisionWorld::RayResultCallback& m_resultCallback; btSingleRayCallback(const btVector3& rayFromWorld, const btVector3& rayToWorld, const btCollisionWorld* world, btCollisionWorld::RayResultCallback& resultCallback) : m_rayFromWorld(rayFromWorld), m_rayToWorld(rayToWorld), m_world(world), m_resultCallback(resultCallback) { m_rayFromTrans.setIdentity(); m_rayFromTrans.setOrigin(m_rayFromWorld); m_rayToTrans.setIdentity(); m_rayToTrans.setOrigin(m_rayToWorld); btVector3 rayDir = (rayToWorld - rayFromWorld); rayDir.normalize(); ///what about division by zero? --> just set rayDirection[i] to INF/BT_LARGE_FLOAT m_rayDirectionInverse[0] = rayDir[0] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[0]; m_rayDirectionInverse[1] = rayDir[1] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[1]; m_rayDirectionInverse[2] = rayDir[2] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[2]; m_signs[0] = m_rayDirectionInverse[0] < 0.0; m_signs[1] = m_rayDirectionInverse[1] < 0.0; m_signs[2] = m_rayDirectionInverse[2] < 0.0; m_lambda_max = rayDir.dot(m_rayToWorld - m_rayFromWorld); } virtual bool process(const btBroadphaseProxy* proxy) { ///terminate further ray tests, once the closestHitFraction reached zero if (m_resultCallback.m_closestHitFraction == btScalar(0.f)) return false; btCollisionObject* collisionObject = (btCollisionObject*)proxy->m_clientObject; //only perform raycast if filterMask matches if (m_resultCallback.needsCollision(collisionObject->getBroadphaseHandle())) { //RigidcollisionObject* collisionObject = ctrl->GetRigidcollisionObject(); //btVector3 collisionObjectAabbMin,collisionObjectAabbMax; #if 0 #ifdef RECALCULATE_AABB btVector3 collisionObjectAabbMin,collisionObjectAabbMax; collisionObject->getCollisionShape()->getAabb(collisionObject->getWorldTransform(),collisionObjectAabbMin,collisionObjectAabbMax); #else //getBroadphase()->getAabb(collisionObject->getBroadphaseHandle(),collisionObjectAabbMin,collisionObjectAabbMax); const btVector3& collisionObjectAabbMin = collisionObject->getBroadphaseHandle()->m_aabbMin; const btVector3& collisionObjectAabbMax = collisionObject->getBroadphaseHandle()->m_aabbMax; #endif #endif //btScalar hitLambda = m_resultCallback.m_closestHitFraction; //culling already done by broadphase //if (btRayAabb(m_rayFromWorld,m_rayToWorld,collisionObjectAabbMin,collisionObjectAabbMax,hitLambda,m_hitNormal)) { m_world->rayTestSingle(m_rayFromTrans, m_rayToTrans, collisionObject, collisionObject->getCollisionShape(), collisionObject->getWorldTransform(), m_resultCallback); } } return true; } }; void btCollisionWorld::rayTest(const btVector3& rayFromWorld, const btVector3& rayToWorld, RayResultCallback& resultCallback) const { //BT_PROFILE(""rayTest""); /// use the broadphase to accelerate the search for objects, based on their aabb /// and for each object with ray-aabb overlap, perform an exact ray test btSingleRayCallback rayCB(rayFromWorld, rayToWorld, this, resultCallback); #ifndef USE_BRUTEFORCE_RAYBROADPHASE m_broadphasePairCache->rayTest(rayFromWorld, rayToWorld, rayCB); #else for (int i = 0; i < this->getNumCollisionObjects(); i++) { rayCB.process(m_collisionObjects[i]->getBroadphaseHandle()); } #endif //USE_BRUTEFORCE_RAYBROADPHASE } struct btSingleSweepCallback : public btBroadphaseRayCallback { btTransform m_convexFromTrans; btTransform m_convexToTrans; btVector3 m_hitNormal; const btCollisionWorld* m_world; btCollisionWorld::ConvexResultCallback& m_resultCallback; btScalar m_allowedCcdPenetration; const btConvexShape* m_castShape; btSingleSweepCallback(const btConvexShape* castShape, const btTransform& convexFromTrans, const btTransform& convexToTrans, const btCollisionWorld* world, btCollisionWorld::ConvexResultCallback& resultCallback, btScalar allowedPenetration) : m_convexFromTrans(convexFromTrans), m_convexToTrans(convexToTrans), m_world(world), m_resultCallback(resultCallback), m_allowedCcdPenetration(allowedPenetration), m_castShape(castShape) { btVector3 unnormalizedRayDir = (m_convexToTrans.getOrigin() - m_convexFromTrans.getOrigin()); btVector3 rayDir = unnormalizedRayDir.normalized(); ///what about division by zero? --> just set rayDirection[i] to INF/BT_LARGE_FLOAT m_rayDirectionInverse[0] = rayDir[0] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[0]; m_rayDirectionInverse[1] = rayDir[1] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[1]; m_rayDirectionInverse[2] = rayDir[2] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[2]; m_signs[0] = m_rayDirectionInverse[0] < 0.0; m_signs[1] = m_rayDirectionInverse[1] < 0.0; m_signs[2] = m_rayDirectionInverse[2] < 0.0; m_lambda_max = rayDir.dot(unnormalizedRayDir); } virtual bool process(const btBroadphaseProxy* proxy) { ///terminate further convex sweep tests, once the closestHitFraction reached zero if (m_resultCallback.m_closestHitFraction == btScalar(0.f)) return false; btCollisionObject* collisionObject = (btCollisionObject*)proxy->m_clientObject; //only perform raycast if filterMask matches if (m_resultCallback.needsCollision(collisionObject->getBroadphaseHandle())) { //RigidcollisionObject* collisionObject = ctrl->GetRigidcollisionObject(); m_world->objectQuerySingle(m_castShape, m_convexFromTrans, m_convexToTrans, collisionObject, collisionObject->getCollisionShape(), collisionObject->getWorldTransform(), m_resultCallback, m_allowedCcdPenetration); } return true; } }; void btCollisionWorld::convexSweepTest(const btConvexShape* castShape, const btTransform& convexFromWorld, const btTransform& convexToWorld, ConvexResultCallback& resultCallback, btScalar allowedCcdPenetration) const { BT_PROFILE(""convexSweepTest""); /// use the broadphase to accelerate the search for objects, based on their aabb /// and for each object with ray-aabb overlap, perform an exact ray test /// unfortunately the implementation for rayTest and convexSweepTest duplicated, albeit practically identical btTransform convexFromTrans, convexToTrans; convexFromTrans = convexFromWorld; convexToTrans = convexToWorld; btVector3 castShapeAabbMin, castShapeAabbMax; /* Compute AABB that encompasses angular movement */ { btVector3 linVel, angVel; btTransformUtil::calculateVelocity(convexFromTrans, convexToTrans, 1.0f, linVel, angVel); btVector3 zeroLinVel; zeroLinVel.setValue(0, 0, 0); btTransform R; R.setIdentity(); R.setRotation(convexFromTrans.getRotation()); castShape->calculateTemporalAabb(R, zeroLinVel, angVel, 1.0f, castShapeAabbMin, castShapeAabbMax); } #ifndef USE_BRUTEFORCE_RAYBROADPHASE btSingleSweepCallback convexCB(castShape, convexFromWorld, convexToWorld, this, resultCallback, allowedCcdPenetration); m_broadphasePairCache->rayTest(convexFromTrans.getOrigin(), convexToTrans.getOrigin(), convexCB, castShapeAabbMin, castShapeAabbMax); #else /// go over all objects, and if the ray intersects their aabb + cast shape aabb, // do a ray-shape query using convexCaster (CCD) int i; for (i = 0; i < m_collisionObjects.size(); i++) { btCollisionObject* collisionObject = m_collisionObjects[i]; //only perform raycast if filterMask matches if (resultCallback.needsCollision(collisionObject->getBroadphaseHandle())) { //RigidcollisionObject* collisionObject = ctrl->GetRigidcollisionObject(); btVector3 collisionObjectAabbMin, collisionObjectAabbMax; collisionObject->getCollisionShape()->getAabb(collisionObject->getWorldTransform(), collisionObjectAabbMin, collisionObjectAabbMax); AabbExpand(collisionObjectAabbMin, collisionObjectAabbMax, castShapeAabbMin, castShapeAabbMax); btScalar hitLambda = btScalar(1.); //could use resultCallback.m_closestHitFraction, but needs testing btVector3 hitNormal; if (btRayAabb(convexFromWorld.getOrigin(), convexToWorld.getOrigin(), collisionObjectAabbMin, collisionObjectAabbMax, hitLambda, hitNormal)) { objectQuerySingle(castShape, convexFromTrans, convexToTrans, collisionObject, collisionObject->getCollisionShape(), collisionObject->getWorldTransform(), resultCallback, allowedCcdPenetration); } } } #endif //USE_BRUTEFORCE_RAYBROADPHASE } struct btBridgedManifoldResult : public btManifoldResult { btCollisionWorld::ContactResultCallback& m_resultCallback; btBridgedManifoldResult(const btCollisionObjectWrapper* obj0Wrap, const btCollisionObjectWrapper* obj1Wrap, btCollisionWorld::ContactResultCallback& resultCallback) : btManifoldResult(obj0Wrap, obj1Wrap), m_resultCallback(resultCallback) { } virtual void addContactPoint(const btVector3& normalOnBInWorld, const btVector3& pointInWorld, btScalar depth) { bool isSwapped = m_manifoldPtr->getBody0() != m_body0Wrap->getCollisionObject(); btVector3 pointA = pointInWorld + normalOnBInWorld * depth; btVector3 localA; btVector3 localB; if (isSwapped) { localA = m_body1Wrap->getCollisionObject()->getWorldTransform().invXform(pointA); localB = m_body0Wrap->getCollisionObject()->getWorldTransform().invXform(pointInWorld); } else { localA = m_body0Wrap->getCollisionObject()->getWorldTransform().invXform(pointA); localB = m_body1Wrap->getCollisionObject()->getWorldTransform().invXform(pointInWorld); } btManifoldPoint newPt(localA, localB, normalOnBInWorld, depth); newPt.m_positionWorldOnA = pointA; newPt.m_positionWorldOnB = pointInWorld; //BP mod, store contact triangles. if (isSwapped) { newPt.m_partId0 = m_partId1; newPt.m_partId1 = m_partId0; newPt.m_index0 = m_index1; newPt.m_index1 = m_index0; } else { newPt.m_partId0 = m_partId0; newPt.m_partId1 = m_partId1; newPt.m_index0 = m_index0; newPt.m_index1 = m_index1; } //experimental feature info, for per-triangle material etc. const btCollisionObjectWrapper* obj0Wrap = isSwapped ? m_body1Wrap : m_body0Wrap; const btCollisionObjectWrapper* obj1Wrap = isSwapped ? m_body0Wrap : m_body1Wrap; m_resultCallback.addSingleResult(newPt, obj0Wrap, newPt.m_partId0, newPt.m_index0, obj1Wrap, newPt.m_partId1, newPt.m_index1); } }; struct btSingleContactCallback : public btBroadphaseAabbCallback { btCollisionObject* m_collisionObject; btCollisionWorld* m_world; btCollisionWorld::ContactResultCallback& m_resultCallback; btSingleContactCallback(btCollisionObject* collisionObject, btCollisionWorld* world, btCollisionWorld::ContactResultCallback& resultCallback) : m_collisionObject(collisionObject), m_world(world), m_resultCallback(resultCallback) { } virtual bool process(const btBroadphaseProxy* proxy) { btCollisionObject* collisionObject = (btCollisionObject*)proxy->m_clientObject; if (collisionObject == m_collisionObject) return true; //only perform raycast if filterMask matches if (m_resultCallback.needsCollision(collisionObject->getBroadphaseHandle())) { btCollisionObjectWrapper ob0(0, m_collisionObject->getCollisionShape(), m_collisionObject, m_collisionObject->getWorldTransform(), -1, -1); btCollisionObjectWrapper ob1(0, collisionObject->getCollisionShape(), collisionObject, collisionObject->getWorldTransform(), -1, -1); btCollisionAlgorithm* algorithm = m_world->getDispatcher()->findAlgorithm(&ob0, &ob1, 0, BT_CLOSEST_POINT_ALGORITHMS); if (algorithm) { btBridgedManifoldResult contactPointResult(&ob0, &ob1, m_resultCallback); //discrete collision detection query algorithm->processCollision(&ob0, &ob1, m_world->getDispatchInfo(), &contactPointResult); algorithm->~btCollisionAlgorithm(); m_world->getDispatcher()->freeCollisionAlgorithm(algorithm); } } return true; } }; ///contactTest performs a discrete collision test against all objects in the btCollisionWorld, and calls the resultCallback. ///it reports one or more contact points for every overlapping object (including the one with deepest penetration) void btCollisionWorld::contactTest(btCollisionObject* colObj, ContactResultCallback& resultCallback) { btVector3 aabbMin, aabbMax; colObj->getCollisionShape()->getAabb(colObj->getWorldTransform(), aabbMin, aabbMax); btSingleContactCallback contactCB(colObj, this, resultCallback); m_broadphasePairCache->aabbTest(aabbMin, aabbMax, contactCB); } ///contactTest performs a discrete collision test between two collision objects and calls the resultCallback if overlap if detected. ///it reports one or more contact points (including the one with deepest penetration) void btCollisionWorld::contactPairTest(btCollisionObject* colObjA, btCollisionObject* colObjB, ContactResultCallback& resultCallback) { btCollisionObjectWrapper obA(0, colObjA->getCollisionShape(), colObjA, colObjA->getWorldTransform(), -1, -1); btCollisionObjectWrapper obB(0, colObjB->getCollisionShape(), colObjB, colObjB->getWorldTransform(), -1, -1); btCollisionAlgorithm* algorithm = getDispatcher()->findAlgorithm(&obA, &obB, 0, BT_CLOSEST_POINT_ALGORITHMS); if (algorithm) { btBridgedManifoldResult contactPointResult(&obA, &obB, resultCallback); contactPointResult.m_closestPointDistanceThreshold = resultCallback.m_closestDistanceThreshold; //discrete collision detection query algorithm->processCollision(&obA, &obB, getDispatchInfo(), &contactPointResult); algorithm->~btCollisionAlgorithm(); getDispatcher()->freeCollisionAlgorithm(algorithm); } } class DebugDrawcallback : public btTriangleCallback, public btInternalTriangleIndexCallback { btIDebugDraw* m_debugDrawer; btVector3 m_color; btTransform m_worldTrans; public: DebugDrawcallback(btIDebugDraw* debugDrawer, const btTransform& worldTrans, const btVector3& color) : m_debugDrawer(debugDrawer), m_color(color), m_worldTrans(worldTrans) { } virtual void internalProcessTriangleIndex(btVector3* triangle, int partId, int triangleIndex) { processTriangle(triangle, partId, triangleIndex); } virtual void processTriangle(btVector3* triangle, int partId, int triangleIndex) { (void)partId; (void)triangleIndex; btVector3 wv0, wv1, wv2; wv0 = m_worldTrans * triangle[0]; wv1 = m_worldTrans * triangle[1]; wv2 = m_worldTrans * triangle[2]; btVector3 center = (wv0 + wv1 + wv2) * btScalar(1. / 3.); if (m_debugDrawer->getDebugMode() & btIDebugDraw::DBG_DrawNormals) { btVector3 normal = (wv1 - wv0).cross(wv2 - wv0); normal.normalize(); btVector3 normalColor(1, 1, 0); m_debugDrawer->drawLine(center, center + normal, normalColor); } m_debugDrawer->drawLine(wv0, wv1, m_color); m_debugDrawer->drawLine(wv1, wv2, m_color); m_debugDrawer->drawLine(wv2, wv0, m_color); } }; void btCollisionWorld::debugDrawObject(const btTransform& worldTransform, const btCollisionShape* shape, const btVector3& color) { // Draw a small simplex at the center of the object if (getDebugDrawer() && getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawFrames) { getDebugDrawer()->drawTransform(worldTransform, .1); } if (shape->getShapeType() == COMPOUND_SHAPE_PROXYTYPE) { const btCompoundShape* compoundShape = static_cast(shape); for (int i = compoundShape->getNumChildShapes() - 1; i >= 0; i--) { btTransform childTrans = compoundShape->getChildTransform(i); const btCollisionShape* colShape = compoundShape->getChildShape(i); debugDrawObject(worldTransform * childTrans, colShape, color); } } else { switch (shape->getShapeType()) { case BOX_SHAPE_PROXYTYPE: { const btBoxShape* boxShape = static_cast(shape); btVector3 halfExtents = boxShape->getHalfExtentsWithMargin(); getDebugDrawer()->drawBox(-halfExtents, halfExtents, worldTransform, color); break; } case SPHERE_SHAPE_PROXYTYPE: { const btSphereShape* sphereShape = static_cast(shape); btScalar radius = sphereShape->getMargin(); //radius doesn't include the margin, so draw with margin getDebugDrawer()->drawSphere(radius, worldTransform, color); break; } case MULTI_SPHERE_SHAPE_PROXYTYPE: { const btMultiSphereShape* multiSphereShape = static_cast(shape); btTransform childTransform; childTransform.setIdentity(); for (int i = multiSphereShape->getSphereCount() - 1; i >= 0; i--) { childTransform.setOrigin(multiSphereShape->getSpherePosition(i)); getDebugDrawer()->drawSphere(multiSphereShape->getSphereRadius(i), worldTransform * childTransform, color); } break; } case CAPSULE_SHAPE_PROXYTYPE: { const btCapsuleShape* capsuleShape = static_cast(shape); btScalar radius = capsuleShape->getRadius(); btScalar halfHeight = capsuleShape->getHalfHeight(); int upAxis = capsuleShape->getUpAxis(); getDebugDrawer()->drawCapsule(radius, halfHeight, upAxis, worldTransform, color); break; } case CONE_SHAPE_PROXYTYPE: { const btConeShape* coneShape = static_cast(shape); btScalar radius = coneShape->getRadius(); //+coneShape->getMargin(); btScalar height = coneShape->getHeight(); //+coneShape->getMargin(); int upAxis = coneShape->getConeUpIndex(); getDebugDrawer()->drawCone(radius, height, upAxis, worldTransform, color); break; } case CYLINDER_SHAPE_PROXYTYPE: { const btCylinderShape* cylinder = static_cast(shape); int upAxis = cylinder->getUpAxis(); btScalar radius = cylinder->getRadius(); btScalar halfHeight = cylinder->getHalfExtentsWithMargin()[upAxis]; getDebugDrawer()->drawCylinder(radius, halfHeight, upAxis, worldTransform, color); break; } case STATIC_PLANE_PROXYTYPE: { const btStaticPlaneShape* staticPlaneShape = static_cast(shape); btScalar planeConst = staticPlaneShape->getPlaneConstant(); const btVector3& planeNormal = staticPlaneShape->getPlaneNormal(); getDebugDrawer()->drawPlane(planeNormal, planeConst, worldTransform, color); break; } default: { /// for polyhedral shapes if (shape->isPolyhedral()) { btPolyhedralConvexShape* polyshape = (btPolyhedralConvexShape*)shape; int i; if (polyshape->getConvexPolyhedron()) { const btConvexPolyhedron* poly = polyshape->getConvexPolyhedron(); for (i = 0; i < poly->m_faces.size(); i++) { btVector3 centroid(0, 0, 0); int numVerts = poly->m_faces[i].m_indices.size(); if (numVerts) { int lastV = poly->m_faces[i].m_indices[numVerts - 1]; for (int v = 0; v < poly->m_faces[i].m_indices.size(); v++) { int curVert = poly->m_faces[i].m_indices[v]; centroid += poly->m_vertices[curVert]; getDebugDrawer()->drawLine(worldTransform * poly->m_vertices[lastV], worldTransform * poly->m_vertices[curVert], color); lastV = curVert; } } centroid *= btScalar(1.f) / btScalar(numVerts); if (getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawNormals) { btVector3 normalColor(1, 1, 0); btVector3 faceNormal(poly->m_faces[i].m_plane[0], poly->m_faces[i].m_plane[1], poly->m_faces[i].m_plane[2]); getDebugDrawer()->drawLine(worldTransform * centroid, worldTransform * (centroid + faceNormal), normalColor); } } } else { for (i = 0; i < polyshape->getNumEdges(); i++) { btVector3 a, b; polyshape->getEdge(i, a, b); btVector3 wa = worldTransform * a; btVector3 wb = worldTransform * b; getDebugDrawer()->drawLine(wa, wb, color); } } } if (shape->isConcave()) { btConcaveShape* concaveMesh = (btConcaveShape*)shape; ///@todo pass camera, for some culling? no -> we are not a graphics lib btVector3 aabbMax(btScalar(BT_LARGE_FLOAT), btScalar(BT_LARGE_FLOAT), btScalar(BT_LARGE_FLOAT)); btVector3 aabbMin(btScalar(-BT_LARGE_FLOAT), btScalar(-BT_LARGE_FLOAT), btScalar(-BT_LARGE_FLOAT)); DebugDrawcallback drawCallback(getDebugDrawer(), worldTransform, color); concaveMesh->processAllTriangles(&drawCallback, aabbMin, aabbMax); } if (shape->getShapeType() == CONVEX_TRIANGLEMESH_SHAPE_PROXYTYPE) { btConvexTriangleMeshShape* convexMesh = (btConvexTriangleMeshShape*)shape; //todo: pass camera for some culling btVector3 aabbMax(btScalar(BT_LARGE_FLOAT), btScalar(BT_LARGE_FLOAT), btScalar(BT_LARGE_FLOAT)); btVector3 aabbMin(btScalar(-BT_LARGE_FLOAT), btScalar(-BT_LARGE_FLOAT), btScalar(-BT_LARGE_FLOAT)); //DebugDrawcallback drawCallback; DebugDrawcallback drawCallback(getDebugDrawer(), worldTransform, color); convexMesh->getMeshInterface()->InternalProcessAllTriangles(&drawCallback, aabbMin, aabbMax); } } } } } void btCollisionWorld::debugDrawWorld() { if (getDebugDrawer()) { getDebugDrawer()->clearLines(); btIDebugDraw::DefaultColors defaultColors = getDebugDrawer()->getDefaultColors(); if (getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawContactPoints) { if (getDispatcher()) { int numManifolds = getDispatcher()->getNumManifolds(); for (int i = 0; i < numManifolds; i++) { btPersistentManifold* contactManifold = getDispatcher()->getManifoldByIndexInternal(i); //btCollisionObject* obA = static_cast(contactManifold->getBody0()); //btCollisionObject* obB = static_cast(contactManifold->getBody1()); int numContacts = contactManifold->getNumContacts(); for (int j = 0; j < numContacts; j++) { btManifoldPoint& cp = contactManifold->getContactPoint(j); getDebugDrawer()->drawContactPoint(cp.m_positionWorldOnB, cp.m_normalWorldOnB, cp.getDistance(), cp.getLifeTime(), defaultColors.m_contactPoint); } } } } if ((getDebugDrawer()->getDebugMode() & (btIDebugDraw::DBG_DrawWireframe | btIDebugDraw::DBG_DrawAabb))) { int i; for (i = 0; i < m_collisionObjects.size(); i++) { btCollisionObject* colObj = m_collisionObjects[i]; if ((colObj->getCollisionFlags() & btCollisionObject::CF_DISABLE_VISUALIZE_OBJECT) == 0) { if (getDebugDrawer() && (getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawWireframe)) { btVector3 color(btScalar(0.4), btScalar(0.4), btScalar(0.4)); switch (colObj->getActivationState()) { case ACTIVE_TAG: color = defaultColors.m_activeObject; break; case ISLAND_SLEEPING: color = defaultColors.m_deactivatedObject; break; case WANTS_DEACTIVATION: color = defaultColors.m_wantsDeactivationObject; break; case DISABLE_DEACTIVATION: color = defaultColors.m_disabledDeactivationObject; break; case DISABLE_SIMULATION: color = defaultColors.m_disabledSimulationObject; break; default: { color = btVector3(btScalar(.3), btScalar(0.3), btScalar(0.3)); } }; colObj->getCustomDebugColor(color); debugDrawObject(colObj->getWorldTransform(), colObj->getCollisionShape(), color); } if (m_debugDrawer && (m_debugDrawer->getDebugMode() & btIDebugDraw::DBG_DrawAabb)) { btVector3 minAabb, maxAabb; btVector3 colorvec = defaultColors.m_aabb; colObj->getCollisionShape()->getAabb(colObj->getWorldTransform(), minAabb, maxAabb); btVector3 contactThreshold(gContactBreakingThreshold, gContactBreakingThreshold, gContactBreakingThreshold); minAabb -= contactThreshold; maxAabb += contactThreshold; btVector3 minAabb2, maxAabb2; if (getDispatchInfo().m_useContinuous && colObj->getInternalType() == btCollisionObject::CO_RIGID_BODY && !colObj->isStaticOrKinematicObject()) { colObj->getCollisionShape()->getAabb(colObj->getInterpolationWorldTransform(), minAabb2, maxAabb2); minAabb2 -= contactThreshold; maxAabb2 += contactThreshold; minAabb.setMin(minAabb2); maxAabb.setMax(maxAabb2); } m_debugDrawer->drawAabb(minAabb, maxAabb, colorvec); } } } } } } void btCollisionWorld::serializeCollisionObjects(btSerializer* serializer) { int i; ///keep track of shapes already serialized btHashMap serializedShapes; for (i = 0; i < m_collisionObjects.size(); i++) { btCollisionObject* colObj = m_collisionObjects[i]; btCollisionShape* shape = colObj->getCollisionShape(); if (!serializedShapes.find(shape)) { serializedShapes.insert(shape, shape); shape->serializeSingleShape(serializer); } } //serialize all collision objects for (i = 0; i < m_collisionObjects.size(); i++) { btCollisionObject* colObj = m_collisionObjects[i]; if (colObj->getInternalType() == btCollisionObject::CO_COLLISION_OBJECT) { colObj->serializeSingleObject(serializer); } } } void btCollisionWorld::serializeContactManifolds(btSerializer* serializer) { if (serializer->getSerializationFlags() & BT_SERIALIZE_CONTACT_MANIFOLDS) { int numManifolds = getDispatcher()->getNumManifolds(); for (int i = 0; i < numManifolds; i++) { const btPersistentManifold* manifold = getDispatcher()->getInternalManifoldPointer()[i]; //don't serialize empty manifolds, they just take space //(may have to do it anyway if it destroys determinism) if (manifold->getNumContacts() == 0) continue; btChunk* chunk = serializer->allocate(manifold->calculateSerializeBufferSize(), 1); const char* structType = manifold->serialize(manifold, chunk->m_oldPtr, serializer); serializer->finalizeChunk(chunk, structType, BT_CONTACTMANIFOLD_CODE, (void*)manifold); } } } void btCollisionWorld::serialize(btSerializer* serializer) { serializer->startSerialization(); serializeCollisionObjects(serializer); serializeContactManifolds(serializer); serializer->finishSerialization(); } ",16352,True,3012.467265965088,median "#include ""core_includes.h"" #include ""os_core_graphics.h"" #include ""core_includes.h"" #include ""FApp.hpp"" #include ""PlatformGraphicsInterface.hpp"" #include ""FFloatBufferCache.hpp"" #include ""FIndexBufferCache.hpp"" #include ""FFileTable.hpp"" #include ""ShaderProgram.hpp"" #include ""OpenGLEngine.hpp"" #include ""FModelDataPacked.hpp"" #if defined(WIN_32_ENV) || defined(MAC_ENVIRONMENT) // // #endif #ifndef glOrthof #define glOrthof glOrtho #endif // #ifndef GL_CLAMP_TO_EDGE #define GL_CLAMP_TO_EDGE GL_CLAMP // #endif static int cArrayBufferDataOffset = -1; static int cArrayBufferPositionsOffset = -1; static int cArrayBufferTextureCoordsOffset = -1; static int cArrayBufferNormalsOffset = -1; static int cArrayBufferTangentsOffset = -1; static int gGraphicsThread = -1; static int cCurrentRenderPass = -1; static int cBufferIndexUniforms = 2; static int cBufferIndexPositions = 0; static int cBufferIndexTextureCoords = 1; static int cBufferIndexNormals = -1; static int cBufferIndexUNormals = -1; static int cBufferIndexTangents = -1; static int cBufferIndexData = 0; static int cBufferIndexTextures = 0; static float cDeviceScale = 1.0f; static float cClipRectBase[4]; static bool cClipEnabled = false; //static bool cDidTearDown = false; ShaderProgram *cShaderProgram = NULL; FMatrix cMatrixProjection; FMatrix cMatrixModelView; FMatrix cMatrixOrtho; FTextureRect cTileRect; //When we create buffers, we add them to this thing... //VideoBuffer FUniforms cUniform; FFloatBufferCacheByteAligned256 cVertexCache; FIndexBufferCache cIndexCache; static FColor cColor; static float cRectBuffer[12]; Graphics::Graphics() { } Graphics::~Graphics() { } void Graphics::Flush() { } void Graphics::Initialize() { //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); BlendEnable(); BlendSetAlpha(); //Graphics::TextureSetClamp(); #if (CURRENT_ENV == ENV_WIN32) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T, GL_CLAMP); #else glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); #endif Graphics::TextureSetFilterLinear(); //Graphics::TextureEnable(); glEnable(GL_TEXTURE_2D); //Graphics::EnableTextureCoordinateArray(); //glEnableClientState(GL_TEXTURE_COORD_ARRAY); //Graphics::EnableVertexArray(); } void Graphics::SetUp() { Log(""Graphics::SetUp() => gOpenGLEngine->SetUp();\\n""); gOpenGLEngine->SetUp(); gTextureCache.ReloadAllTextures(); gBufferCache.ReloadAllBuffers(); /* if (cDidTearDown) { cDidTearDown = false; gOpenGLEngine->SetUp(); gTextureCache.ReloadAllTextures(); gBufferCache.ReloadAllBuffers(); EnumList(FSprite, aSprite, gSpriteList) { aSprite->WriteBuffers(); Log(""Sprite Name: %s\\n"", aSprite->mFileName.c()); } //EnumList(FModelDataPacked, aModel, gPackedModelList) { // aModel->WriteBuffers(); //} } */ } //Before we lose out content, we TEAR DOWN. void Graphics::TearDown() { Log(""Graphics::TearDown()\\n""); if (gOpenGLEngine) { Log(""Graphics::TearDown() => gOpenGLEngine->SetUp();\\n""); gOpenGLEngine->TearDown(); } //cDidTearDown = true; gTextureCache.UnloadAllTextures(); gBufferCache.UnloadAllBuffers(); } void Graphics::SetDeviceScale(float pScale) { cDeviceScale = pScale; } void Graphics::SetDeviceSize(float pWidth, float pHeight) { FMatrix aOrtho = FMatrixCreateOrtho(0.0f, pWidth, pHeight, 0.0f, -2048.0f, 2048.0f); cMatrixOrtho.Set(aOrtho); Graphics::ViewportSet(0.0f, 0.0f, pWidth, pHeight); Graphics::ClipSetAppFrame(0.0f, 0.0f, pWidth, pHeight); cTileRect.SetRect(0.0f, 0.0f, pWidth, pHeight); } void Graphics::PreRender() { cVertexCache.Reset(); cIndexCache.Reset(); cCurrentRenderPass = -1; cShaderProgram = NULL; cArrayBufferDataOffset = -999; cArrayBufferPositionsOffset = -999; cArrayBufferTextureCoordsOffset = -999; cArrayBufferNormalsOffset = -999; cArrayBufferTangentsOffset = -999; } void Graphics::PostRender() { cCurrentRenderPass = -1; } void Graphics::DrawQuad(float pX1, float pY1, float pX2, float pY2, float pX3, float pY3, float pX4, float pY4) { FBuffer *aBufferPosition = gBufferCache.GetArrayBuffer(sizeof(float) * 8); if (aBufferPosition == NULL) { return; } if (aBufferPosition->mBindIndex == -1) { return; } cRectBuffer[0] = pX1; cRectBuffer[1] = pY1; cRectBuffer[2] = pX2; cRectBuffer[3] = pY2; cRectBuffer[4] = pX3; cRectBuffer[5] = pY3; cRectBuffer[6] = pX4; cRectBuffer[7] = pY4; BufferArrayWrite(aBufferPosition, cRectBuffer, 0, sizeof(float) * 8); ArrayBufferPositions(aBufferPosition, 0); UniformBind(); DrawTriangleStrips(4); // // // } void Graphics::DrawQuad(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { cRectBuffer[0]=x1; cRectBuffer[1]=y1; cRectBuffer[2]=z1; cRectBuffer[3]=x2; cRectBuffer[4]=y2; cRectBuffer[5]=z2; cRectBuffer[6]=x3; cRectBuffer[7]=y3; cRectBuffer[8]=z3; cRectBuffer[9]=x4; cRectBuffer[10]=y4; cRectBuffer[11]=z4; FBuffer *aPositionsBuffer = gBufferCache.GetArrayBuffer(sizeof(float) * 12); if (aPositionsBuffer != NULL && aPositionsBuffer->mBindIndex != -1) { BufferArrayWrite(aPositionsBuffer, cRectBuffer, 0, sizeof(float) * 12); ArrayBufferPositions(aPositionsBuffer, 0); DrawTriangleStrips(4); } /* cVertexCache.Get(sizeof(float) * 12); if (cVertexCache.mResult.mSuccess) { FBuffer *aPositionsBuffer = cVertexCache.mResult.mBuffer; int aPositionsBufferOffset = cVertexCache.mResult.mBufferOffset; BufferArrayWrite(aPositionsBuffer, cRectBuffer, aPositionsBufferOffset, sizeof(float) * 12); ArrayBufferPositions(aPositionsBuffer, aPositionsBufferOffset); } //TODO: Bind Uni? //This will MESS UP menu ?? //UniformBind(); DrawTriangleStrips(4); */ } void Graphics::SetColor(float pRed, float pGreen, float pBlue, float pAlpha) { cColor.mRed = pRed; cColor.mGreen = pGreen; cColor.mBlue = pBlue; cColor.mAlpha = pAlpha; } void Graphics::SetColor(float pRed, float pGreen, float pBlue){Graphics::SetColor(pRed,pGreen,pBlue,1);} void Graphics::SetColor(float pIntensity){Graphics::SetColor(1,1,1,pIntensity);} void Graphics::SetColor(){Graphics::SetColor(1,1,1,1);} void Graphics::SetColor(FColor pColor){Graphics::SetColor(pColor.mRed,pColor.mGreen,pColor.mBlue,pColor.mAlpha);} void Graphics::SetColorHex(int pRed, int pGreen, int pBlue, int pAlpha) { Graphics::SetColor((float)pRed/255.0f, (float)pGreen/255.0f, (float)pBlue/255.0f, (float)pAlpha/255.0f); } void Graphics::SetColorHex(int pRed, int pGreen, int pBlue) { SetColorHex(pRed, pGreen, pBlue, 255); } void Graphics::SetColorHex(int pAlpha) { SetColorHex(255,255,255,pAlpha); } void Graphics::DrawTriangle2D(float pX1, float pY1, float pX2, float pY2, float pX3, float pY3) { // cRectBuffer[0] = pX1; cRectBuffer[1] = pY1; cRectBuffer[2] = pX2; cRectBuffer[3] = pY2; cRectBuffer[4] = pX3; cRectBuffer[5] = pY3; // cVertexCache.Get(sizeof(float) * 6); if (cVertexCache.mResult.mSuccess) { FBuffer *aPositionsBuffer = cVertexCache.mResult.mBuffer; int aPositionsBufferOffset = cVertexCache.mResult.mBufferOffset; BufferArrayWrite(aPositionsBuffer, cRectBuffer, aPositionsBufferOffset, sizeof(float) * 6); ArrayBufferPositions(aPositionsBuffer, aPositionsBufferOffset); } // UniformBind(); DrawTriangles(3); } void Graphics::DrawRect(float pX, float pY, float pWidth, float pHeight) { DrawQuad(pX, pY, pX + pWidth, pY, pX, pY + pHeight, pX + pWidth, pY + pHeight); } void Graphics::OutlineRect(float pX, float pY, float pWidth, float pHeight, float pThickness) { DrawRect(pX-pThickness, pY-pThickness, pWidth + pThickness * 2, pThickness); DrawRect(pX-pThickness, pY+pHeight, pWidth + pThickness * 2, pThickness); DrawRect(pX-pThickness, pY, pThickness, pHeight); DrawRect(pX+pWidth, pY, pThickness, pHeight); } void Graphics::OutlineRectInside(float pX, float pY, float pWidth, float pHeight, float pThickness) { OutlineRect(pX + pThickness, pY + pThickness, pWidth - pThickness * 2, pHeight - pThickness * 2, pThickness); } void Graphics::OutlineRect(FRect pRect, float pThickness) { OutlineRect(pRect.mX, pRect.mY, pRect.mWidth, pRect.mHeight, pThickness); } void Graphics::OutlineRectInside(FRect pRect, float pThickness) { OutlineRectInside(pRect.mX, pRect.mY, pRect.mWidth, pRect.mHeight, pThickness); } void Graphics::SetColorSwatch(int pSwatchIndex, float pAlpha) { bool aSign = pSwatchIndex < 0; if (aSign) { pSwatchIndex = (-pSwatchIndex); } if (pSwatchIndex >= 8) { pSwatchIndex = (pSwatchIndex % 8); } if (aSign) { pSwatchIndex = (8 - pSwatchIndex); } if (pSwatchIndex==0) { Graphics::SetColor(1,0,0, pAlpha); } else if(pSwatchIndex == 1) { Graphics::SetColor(0,1,0, pAlpha); } else if(pSwatchIndex == 2) { Graphics::SetColor(0,0,1, pAlpha); } else if(pSwatchIndex == 3) { Graphics::SetColor(0.5f,1,1, pAlpha); } else if(pSwatchIndex == 4) { Graphics::SetColor(1,0.5f,1, pAlpha); } else if(pSwatchIndex==5) { Graphics::SetColor(1,1,0.5, pAlpha); } else if(pSwatchIndex==6) { Graphics::SetColor(1,0.5f,0.5, pAlpha); } else if(pSwatchIndex==7) { Graphics::SetColor(0.5f,1,0.5, pAlpha); } else { Graphics::SetColor(0.5f,0.5f,1, pAlpha); } } void Graphics::SetColorSwatch(int pSwatchIndex) { SetColorSwatch(pSwatchIndex, 1.0f); } void Graphics::DrawLine(float pX1, float pY1, float pX2, float pY2) { DrawLine(pX1, pY1, pX2, pY2, 1.0f); } void Graphics::DrawLine(float pX1, float pY1, float pX2, float pY2, float pThickness) { float aDirX = pX2 - pX1; float aDirY = pY2 - pY1; float aDist = sqrtf((aDirX * aDirX) + (aDirY * aDirY)); aDirX /= aDist; aDirY /= aDist; float aHold = aDirX; aDirX=-aDirY; aDirY=aHold; aDirX*=pThickness; aDirY*=pThickness; DrawQuad(pX2-aDirX, pY2-aDirY, pX2+aDirX, pY2+aDirY, pX1-aDirX, pY1-aDirY, pX1+aDirX, pY1+aDirY); } void Graphics::DrawPoint(float pX, float pY, float pSize) { DrawRect(pX-pSize/2, pY-pSize/2, pSize, pSize); } void Graphics::DrawArrow(float pStartX, float pStartY, float pEndX, float pEndY, float pHeadLength, float pThickness) { DrawLine(pStartX, pStartY, pEndX, pEndY, pThickness); float aDiffX = pStartX - pEndX; float aDiffY = pStartY - pEndY; float aAngle = RADIANS_TO_DEGREES(atan2f(aDiffX, aDiffY)); float aAngle1 = aAngle + 35; float aAngle2 = aAngle - 35; DrawLine(pEndX, pEndY, pEndX + Sin(aAngle1) * pHeadLength, pEndY + Cos(aAngle1) * pHeadLength, pThickness); DrawLine(pEndX, pEndY, pEndX + Sin(aAngle2) * pHeadLength, pEndY + Cos(aAngle2) * pHeadLength, pThickness); } void Graphics::DrawBox(float x1, float y1, float z1, float x2, float y2, float z2, float pSize, float pRotation) { float aDirX = x2 - x1; float aDirY = y2 - y1; float aDirZ = z2 - z1; float aLength = aDirX * aDirX + aDirY * aDirY + aDirZ * aDirZ; if (aLength < SQRT_EPSILON) { aDirX = 0.0f; aDirY = 0.0f; aDirZ = 1.0f; } else { aLength = (float)sqrtf(aLength); aDirX /= aLength; aDirY /= aLength; aDirZ /= aLength; } Graphics::CullFacesSetDisabled(); FVec3 aReference = FVec3(aDirX, aDirY, aDirZ); FVec3 aAxis = FVec3(aDirX, aDirY, aDirZ); //Pick the ""optimal"" orthogonal... float aFactorX = fabsf(aReference.mX); float aFactorY = fabsf(aReference.mY); float aFactorZ = fabsf(aReference.mZ); // (1, 1, 1) // Ortho (-1, 1, 1) if (aFactorX < 0.00025f) { if (aFactorY < 0.00025f) { //Z only, go straight up or left... aReference = FVec3(0.0f, 1.0f, 0.0f); } else { //Y and Z only, flip them... aReference = FVec3(0.0f, -aReference.mZ, aReference.mY); } //aReference = FVec3(1.0f, 0.0f, 0.0f); } else if (aFactorY < 0.00025f) { if (aFactorZ < 0.00025f) { //X only, go straight up or in... aReference = FVec3(0.0f, -1.0f, 0.0f); } else { //X and Z only, flip them... aReference = FVec3(-aReference.mZ, 0.0f, aReference.mX); } } else if (aFactorZ < 0.00025f) { //X and Y only, flip them... aReference = FVec3(-aReference.mY, aReference.mX, 0.0f); } else { aReference = FVec3(1.0f, 1.0f, -((aAxis.mX + aAxis.mY) / aAxis.mZ)); } aReference.Normalize(); FVec3 aPerp1 = Rotate3DNormalized(aReference, aAxis, 0.0f + pRotation); FVec3 aPerp2 = Rotate3DNormalized(aReference, aAxis, 90.0f + pRotation); FVec3 aPerp3 = Rotate3DNormalized(aReference, aAxis, 180.0f + pRotation); FVec3 aPerp4 = Rotate3DNormalized(aReference, aAxis, 270.0f + pRotation); static float aCornerX1[4]; static float aCornerY1[4]; static float aCornerZ1[4]; static float aCornerX2[4]; static float aCornerY2[4]; static float aCornerZ2[4]; float aSize = (pSize / 2.0f); aPerp1 *= aSize; aPerp2 *= aSize; aPerp3 *= aSize; aPerp4 *= aSize; aCornerX1[0] = x1 + aPerp1.mX; aCornerY1[0] = y1 + aPerp1.mY; aCornerZ1[0] = z1 + aPerp1.mZ; aCornerX1[1] = x1 + aPerp2.mX; aCornerY1[1] = y1 + aPerp2.mY; aCornerZ1[1] = z1 + aPerp2.mZ; aCornerX1[2] = x1 + aPerp3.mX; aCornerY1[2] = y1 + aPerp3.mY; aCornerZ1[2] = z1 + aPerp3.mZ; aCornerX1[3] = x1 + aPerp4.mX; aCornerY1[3] = y1 + aPerp4.mY; aCornerZ1[3] = z1 + aPerp4.mZ; // // // // // // // // // // // // // aCornerX2[0] = x2 + aPerp1.mX; aCornerY2[0] = y2 + aPerp1.mY; aCornerZ2[0] = z2 + aPerp1.mZ; aCornerX2[1] = x2 + aPerp2.mX; aCornerY2[1] = y2 + aPerp2.mY; aCornerZ2[1] = z2 + aPerp2.mZ; aCornerX2[2] = x2 + aPerp3.mX; aCornerY2[2] = y2 + aPerp3.mY; aCornerZ2[2] = z2 + aPerp3.mZ; aCornerX2[3] = x2 + aPerp4.mX; aCornerY2[3] = y2 + aPerp4.mY; aCornerZ2[3] = z2 + aPerp4.mZ; //TODO: Do we want this? UniformBind(); DrawQuad(aCornerX1[0], aCornerY1[0], aCornerZ1[0], aCornerX2[0], aCornerY2[0], aCornerZ2[0], aCornerX1[1], aCornerY1[1], aCornerZ1[1], aCornerX2[1], aCornerY2[1], aCornerZ2[1]); DrawQuad(aCornerX1[1], aCornerY1[1], aCornerZ1[1], aCornerX2[1], aCornerY2[1], aCornerZ2[1], aCornerX1[2], aCornerY1[2], aCornerZ1[2], aCornerX2[2], aCornerY2[2], aCornerZ2[2]); DrawQuad(aCornerX1[2], aCornerY1[2], aCornerZ1[2], aCornerX2[2], aCornerY2[2], aCornerZ2[2], aCornerX1[3], aCornerY1[3], aCornerZ1[3], aCornerX2[3], aCornerY2[3], aCornerZ2[3]); DrawQuad(aCornerX1[3], aCornerY1[3], aCornerZ1[3], aCornerX2[3], aCornerY2[3], aCornerZ2[3], aCornerX1[0], aCornerY1[0], aCornerZ1[0], aCornerX2[0], aCornerY2[0], aCornerZ2[0]); // // Cap ends... // DrawQuad(aCornerX1[0], aCornerY1[0], aCornerZ1[0], aCornerX1[3], aCornerY1[3], aCornerZ1[3], aCornerX1[1], aCornerY1[1], aCornerZ1[1], aCornerX1[2], aCornerY1[2], aCornerZ1[2]); DrawQuad(aCornerX2[0], aCornerY2[0], aCornerZ2[0], aCornerX2[1], aCornerY2[1], aCornerZ2[1], aCornerX2[3], aCornerY2[3], aCornerZ2[3], aCornerX2[2], aCornerY2[2], aCornerZ2[2]); } void Graphics::DepthEnable() { glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glDepthMask(GL_TRUE); } void Graphics::DepthDisable() { glDisable(GL_DEPTH_TEST); } void Graphics::DepthClear() { glClear(GL_DEPTH_BUFFER_BIT); } void Graphics::Clear(float pRed, float pGreen, float pBlue, float pAlpha) { // ... This is handled by Metal glClearColor(pRed, pGreen, pBlue, pAlpha); glClear(GL_COLOR_BUFFER_BIT); } void Graphics::Clear(float pRed, float pGreen, float pBlue) { Clear(pRed, pGreen, pBlue, 1.0f); } void Graphics::Clear() { Clear(0.0f, 0.0f, 0.0f, 1.0f); } void Graphics::TextureSetWrap() { //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,GL_REPEAT); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } void Graphics::TextureSetClamp() { #if (CURRENT_ENV == ENV_WIN32) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T, GL_CLAMP); #else glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); #endif } void Graphics::TextureSetFilterMipMap() { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR); } void Graphics::TextureSetFilterLinear() { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } void Graphics::ArrayBufferData(FBuffer *pBuffer) { ArrayBufferData(pBuffer, 0); } void Graphics::ArrayBufferData(FBuffer *pBuffer, int pOffset) { if (cShaderProgram == NULL) { Log(""ArrayBufferPositionsS Fails...\\n""); return; } cShaderProgram->ArrayBufferData(pBuffer, pOffset); } void Graphics::ArrayBufferPositions(FBuffer *pBuffer) { ArrayBufferPositions(pBuffer, 0); } void Graphics::ArrayBufferPositions(FBuffer *pBuffer, int pOffset) { if (cShaderProgram == NULL) { Log(""ArrayBufferPositionsS Fails...\\n""); return; } cShaderProgram->ArrayBufferPositions(pBuffer, pOffset); } void Graphics::ArrayBufferTextureCoords(FBuffer *pBuffer) { ArrayBufferTextureCoords(pBuffer, 0); } void Graphics::ArrayBufferTextureCoords(FBuffer *pBuffer, int pOffset) { if (cShaderProgram == NULL) { Log(""ArrayBufferTextureCoordsS Fails...\\n""); return; } cShaderProgram->ArrayBufferTextureCoords(pBuffer, pOffset); } void Graphics::ArrayBufferColors(FBuffer *pBuffer) { ArrayBufferColors(pBuffer, 0); } void Graphics::ArrayBufferColors(FBuffer *pBuffer, int pOffset) { if (cShaderProgram == NULL) { Log(""ArrayBufferColorsS Fails...\\n""); return; } cShaderProgram->ArrayBufferColors(pBuffer, pOffset); } void Graphics::ArrayBufferNormals(FBuffer *pBuffer) { ArrayBufferNormals(pBuffer, 0); } void Graphics::ArrayBufferNormals(FBuffer *pBuffer, int pOffset) { if (cShaderProgram == NULL) { Log(""ArrayBufferNormalsS Fails...\\n""); return; } cShaderProgram->ArrayBufferNormals(pBuffer, pOffset); } void Graphics::ArrayBufferTangents(FBuffer *pBuffer) { ArrayBufferTangents(pBuffer, 0); } void Graphics::ArrayBufferTangents(FBuffer *pBuffer, int pOffset) { //ShaderProgram->ArrayBufferTangents(<#int pIndex#>, <#int pOffset#>) Log(""ArrayBufferTangents - NOT IMPLEMENTED - EXITING...\\n""); exit(0); } FBuffer *Graphics::ArrayWriteData(void *pData, int pCount) { if (pCount > 0) { FBuffer *aDataBuffer = gBufferCache.GetArrayBuffer(pCount); if (aDataBuffer != NULL && aDataBuffer->mBindIndex != -1) { BufferArrayWrite(aDataBuffer, pData, pCount); ArrayBufferData(aDataBuffer); return aDataBuffer; } } return NULL; } void Graphics::UniformBind() { cUniform.mProjection.Set(cMatrixProjection); cUniform.mModelView.Set(cMatrixModelView); cUniform.mColor = cColor; UniformBind(&cUniform); } void Graphics::UniformBind(FUniforms *pUniforms) { if (cShaderProgram != NULL && pUniforms != NULL) { cShaderProgram->BindUniform(pUniforms); } else { Log(""** Illegally Trying To Bind [%x] [%x]\\n"", cShaderProgram, pUniforms); } } int Graphics::TextureGenerate(unsigned int *pData, int pWidth, int pHeight) { int aBindIndex = -1; glGenTextures(1, (GLuint*)(&aBindIndex)); if (aBindIndex == -1) { Log(""Error Binding Texture [%d x %d]\\n"", pWidth, pHeight); } else { TextureSetData(aBindIndex, pData, pWidth, pHeight); } return aBindIndex; } void Graphics::TextureDelete(int pIndex) { if (pIndex != -1) { glDeleteTextures(1, (GLuint*)(&(pIndex))); } } void Graphics::TextureSetData(int pIndex, unsigned int *pData, int pWidth, int pHeight) { glPixelStorei(GL_UNPACK_ALIGNMENT, 4); TextureBind(pIndex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, pWidth, pHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, pData); } void Graphics::TextureBind(int pIndex) { glBindTexture(GL_TEXTURE_2D, pIndex); } void Graphics::TextureBind(FTexture *pTexture) { if (pTexture) { TextureBind(pTexture->mBindIndex); } } int Graphics::BufferArrayGenerate(int pLength) { unsigned int aBindIndex = 0; if (pLength > 0) { glGenBuffers(1, &aBindIndex); if (aBindIndex != 0) { glBindBuffer(GL_ARRAY_BUFFER, aBindIndex); glBufferData(GL_ARRAY_BUFFER, pLength, 0, GL_DYNAMIC_DRAW); } else { GLenum aError = glGetError(); Log(""Failed To Make Buffer[%d] Err[%d]\\n"", pLength, aError); } } else { Log(""Creating Invalid Sized Buffer... [%d]\\n"", pLength); } return aBindIndex; //glBindBuffer(GL_ARRAY_BUFFER, pBufferIndex); //glBufferData(GL_ARRAY_BUFFER, pSize * 4, pData, GL_STATIC_DRAW); //GL_ELEMENT_ARRAY_BUFFER } void Graphics::BufferArrayWrite(FBuffer *pBuffer, void *pData, int pLength) { //BufferArrayWrite(pBuffer, pData, 0, pLength); if (pBuffer != NULL && pBuffer->mBindIndex != -1) { glBindBuffer(GL_ARRAY_BUFFER, pBuffer->mBindIndex); glBufferData(GL_ARRAY_BUFFER, pLength, pData, GL_STATIC_DRAW); //glBufferSubData(GL_ARRAY_BUFFER, pOffset, pLength, pData); } } void Graphics::BufferArrayWrite(FBuffer *pBuffer, void *pData, int pOffset, int pLength) { if (pBuffer != NULL && pBuffer->mBindIndex != -1) { glBindBuffer(GL_ARRAY_BUFFER, pBuffer->mBindIndex); glBufferSubData(GL_ARRAY_BUFFER, pOffset, pLength, pData); } //glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid* data) OPENGLES_DEPRECATED(ios(3.0, 12.0), tvos(9.0, 12.0)); } void Graphics::BufferArrayDelete(int pIndex) { if (pIndex != -1) { glDeleteBuffers(1, (unsigned int *)(&(pIndex))); } } int Graphics::BufferElementGenerate(int pLength) { unsigned int aBindIndex = -1; if (pLength > 0) { glGenBuffers(1, &aBindIndex); if (aBindIndex != -1) { Log(""Create Element Buffer [%d] Sized[%d]\\n"", aBindIndex, pLength); glBufferData(GL_ELEMENT_ARRAY_BUFFER, pLength, 0, GL_STATIC_DRAW); } else { Log(""Failed To Make Element Buffer[%d]\\n"", pLength); } } else { Log(""Creating Invalid Sized Element Buffer... [%d]\\n"", pLength); } return aBindIndex; } void Graphics::BufferElementWrite(FBuffer *pBuffer, void *pData, int pLength) { BufferElementWrite(pBuffer, pData, 0, pLength); } void Graphics::BufferElementWrite(FBuffer *pBuffer, void *pData, int pOffset, int pLength) { if (pBuffer != NULL && pBuffer->mBindIndex != -1) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, pBuffer->mBindIndex); glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, pOffset, pLength, pData); } } void Graphics::BufferElementDelete(int pIndex) { if (pIndex != -1) { glDeleteBuffers(1, (unsigned int *)(&(pIndex))); } } void Graphics::BufferSetUniformsIndex(int pIndex) { cBufferIndexUniforms = pIndex; } void Graphics::BufferSetPositionsIndex(int pIndex) { cBufferIndexPositions = pIndex; } void Graphics::BufferSetTextureCoordsIndex(int pIndex) { cBufferIndexTextureCoords = pIndex; } void Graphics::BufferSetNormalsIndex(int pIndex) { cBufferIndexNormals = pIndex; } void Graphics::BufferSetTangentsIndex(int pIndex) { cBufferIndexTangents = pIndex; } void Graphics::BufferSetUNormalsIndex(int pIndex) { cBufferIndexUNormals = pIndex; } void Graphics::BufferSetDataIndex(int pIndex) { cBufferIndexData = pIndex; } void Graphics::BufferSetTexturesIndex(int pIndex) { cBufferIndexTextures = pIndex; } void Graphics::BufferSetIndicesShape() { Graphics::BufferSetPositionsIndex(GFX_BUFFER_INDEX_POSITIONS_SHAPE); Graphics::BufferSetTextureCoordsIndex(-1); Graphics::BufferSetNormalsIndex(-1); Graphics::BufferSetTangentsIndex(-1); Graphics::BufferSetUNormalsIndex(-1); Graphics::BufferSetDataIndex(-1); Graphics::BufferSetUniformsIndex(GFX_BUFFER_INDEX_UNIFORMS_SHAPE); } void Graphics::BufferSetIndicesShapeNode() { Graphics::BufferSetPositionsIndex(GFX_BUFFER_INDEX_DATA_SHAPE_NODE); Graphics::BufferSetTextureCoordsIndex(-1); Graphics::BufferSetNormalsIndex(-1); Graphics::BufferSetTangentsIndex(-1); Graphics::BufferSetUNormalsIndex(-1); Graphics::BufferSetDataIndex(-1); Graphics::BufferSetUniformsIndex(GFX_BUFFER_INDEX_UNIFORMS_SHAPE_NODE); } void Graphics::BufferSetIndicesSprite() { Graphics::BufferSetPositionsIndex(GFX_BUFFER_INDEX_POSITIONS_SPRITE); Graphics::BufferSetTextureCoordsIndex(GFX_BUFFER_INDEX_TEXTURE_COORDS_SPRITE); Graphics::BufferSetNormalsIndex(-1); Graphics::BufferSetTangentsIndex(-1); Graphics::BufferSetUNormalsIndex(-1); Graphics::BufferSetDataIndex(-1); Graphics::BufferSetUniformsIndex(GFX_BUFFER_INDEX_UNIFORMS_SPRITE); } void Graphics::BufferSetIndicesSimpleModel() { Graphics::BufferSetPositionsIndex(GFX_BUFFER_INDEX_POSITIONS_SIMPLE_MODEL); Graphics::BufferSetTextureCoordsIndex(GFX_BUFFER_INDEX_TEXTURE_COORDS_SIMPLE_MODEL); Graphics::BufferSetNormalsIndex(-1); Graphics::BufferSetTangentsIndex(-1); Graphics::BufferSetUNormalsIndex(-1); Graphics::BufferSetDataIndex(-1); Graphics::BufferSetUniformsIndex(GFX_BUFFER_INDEX_UNIFORMS_SIMPLE_MODEL); } void Graphics::BufferSetIndicesSimpleModelIndexed() { Graphics::BufferSetPositionsIndex(-1); Graphics::BufferSetTextureCoordsIndex(-1); Graphics::BufferSetNormalsIndex(-1); Graphics::BufferSetTangentsIndex(-1); Graphics::BufferSetUNormalsIndex(-1); Graphics::BufferSetDataIndex(GFX_BUFFER_INDEX_DATA_INDEXED_SIMPLE_MODEL); Graphics::BufferSetUniformsIndex(GFX_BUFFER_INDEX_UNIFORMS_INDEXED_SIMPLE_MODEL); } void Graphics::BufferSetIndicesModelIndexed() { Graphics::BufferSetPositionsIndex(-1); Graphics::BufferSetTextureCoordsIndex(-1); Graphics::BufferSetNormalsIndex(-1); Graphics::BufferSetTangentsIndex(-1); Graphics::BufferSetUNormalsIndex(-1); Graphics::BufferSetDataIndex(GFX_BUFFER_INDEX_DATA_INDEXED_MODEL); Graphics::BufferSetUniformsIndex(GFX_BUFFER_INDEX_UNIFORMS_INDEXED_MODEL); } void Graphics::ClipEnable() { if (cClipEnabled == false) { cClipEnabled = true; glEnable(GL_SCISSOR_TEST); /* glEnable(GLenum(GL_SCISSOR_TEST)) glScissor(GLint(clipRect.origin.x), GLint(clipRect.origin.y), GLsizei(clipRect.size.width), GLsizei(clipRect.size.height)) */ } } void Graphics::ClipDisable() { //if (cClipEnabled) { cClipEnabled = false; //Clip(0.0f, 0.0f, gDeviceWidth, gDeviceHeight); glDisable(GL_SCISSOR_TEST); } //static double cClipPlane[4][4] = { { 0.0f, 1.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f, 0.0f }, { -1.0f, 0.0f, 0.0f, 512.0f }, { 0.0f, -1.0f, 0.0f, 512.0f } }; void Graphics::Clip(float pX, float pY, float pWidth, float pHeight) { int aMaxX = gDeviceWidth * cDeviceScale; int aMaxY = gDeviceHeight * cDeviceScale; int aLeft = roundf(pX); int aTop = roundf(pY); int aWidth = (int)(pWidth + 0.5f); int aHeight = (int)(pHeight + 0.5f); aLeft *= cDeviceScale; aTop *= cDeviceScale; aWidth *= cDeviceScale; aHeight *= cDeviceScale; if (aLeft < 0) { aWidth += aLeft; aLeft = 0; } if (aTop < 0) { aHeight += aTop; aTop = 0; } int aRight = aLeft + aWidth; if (aRight > aMaxX) { aWidth -= (aRight - aMaxX); } int aBottom = aTop + aHeight; if (aBottom > aMaxY) { aHeight -= (aBottom - aMaxY); } if (aWidth < 0) { return; } if (aHeight < 0) { return; } glScissor(aLeft, gDeviceHeight * cDeviceScale - (aTop + aHeight), aWidth, aHeight); } void Graphics::ClipSetAppFrame(float pX, float pY, float pWidth, float pHeight) { cClipRectBase[0] = pX; cClipRectBase[1] = pY; cClipRectBase[2] = pWidth; cClipRectBase[3] = pHeight; } void Graphics::ViewportSet(float pX, float pY, float pWidth, float pHeight) { glViewport(pX, pY, pWidth, pHeight); } void Graphics::DrawModelEfficientSetup(float *pPositions, float *pTextureCoords, float *pNormals, FTexture *pTexture) { } void Graphics::DrawModelIndexedEfficientSetup(float *pPositions, float *pTextureCoords, float *pNormals, FTexture *pTexture) { } void Graphics::DrawModelIndexed(float *pPositions, int pPositionsCount, float *pTextureCoords, int pTextureCoordsCount, float *pNormals, int pNormalsCount, GFX_MODEL_INDEX_TYPE *pIndex, int pCount, FTexture *pTexture) { if (pTexture == NULL || pTexture->mBindIndex == -1) { return; } if (pPositions != NULL && cBufferIndexPositions != -1 && pPositionsCount > 0) { cVertexCache.Get(sizeof(float) * pPositionsCount * 3); if (cVertexCache.mResult.mSuccess) { FBuffer *aPositionsBuffer = cVertexCache.mResult.mBuffer; int aPositionsBufferOffset = cVertexCache.mResult.mBufferOffset; BufferArrayWrite(aPositionsBuffer, pPositions, aPositionsBufferOffset, sizeof(float) * pPositionsCount * 3); ArrayBufferPositions(aPositionsBuffer, aPositionsBufferOffset); } } if (pTextureCoords != NULL && cBufferIndexTextureCoords != -1 && pTextureCoordsCount > 0) { cVertexCache.Get(sizeof(float) * pTextureCoordsCount * 3); if (cVertexCache.mResult.mSuccess) { FBuffer *aTextureCoordsBuffer = cVertexCache.mResult.mBuffer; int aTextureCoordsBufferOffset = cVertexCache.mResult.mBufferOffset; BufferArrayWrite(aTextureCoordsBuffer, pTextureCoords, aTextureCoordsBufferOffset, sizeof(float) * pTextureCoordsCount * 3); ArrayBufferTextureCoords(aTextureCoordsBuffer, aTextureCoordsBufferOffset); } } if (pNormals != NULL && cBufferIndexNormals != -1 && pNormalsCount > 0) { cVertexCache.Get(sizeof(float) * pNormalsCount * 3); if (cVertexCache.mResult.mSuccess) { FBuffer *aNormalsBuffer = cVertexCache.mResult.mBuffer; int aNormalsBufferOffset = cVertexCache.mResult.mBufferOffset; BufferArrayWrite(aNormalsBuffer, pTextureCoords, aNormalsBufferOffset, sizeof(float) * pNormalsCount * 3); ArrayBufferNormals(aNormalsBuffer, aNormalsBufferOffset); } } ///////////////////// // TextureBind(pTexture); UniformBind(); // //DrawTriangles(pCount); //DrawTrianglesIndexed(pIndex, pCount / 3); DrawTrianglesIndexed(pIndex, pCount); } void Graphics::DrawModelIndexed(float *pPositions, int pPositionsCount, float *pTextureCoords, int pTextureCoordsCount, float *pNormals, int pNormalsCount, GFX_MODEL_INDEX_TYPE *pIndex, FTexture *pTexture, int pStartIndex, int pEndIndex) { DrawModelIndexed(pPositions, pPositionsCount, pTextureCoords, pTextureCoordsCount, pNormals, pNormalsCount, pIndex + pStartIndex, (pEndIndex - pStartIndex) + 1, pTexture); } void Graphics::DrawModel(float *pPositions, float *pTextureCoords, float *pNormals, int pCount, FTexture *pTexture) { if (pTexture == NULL || pTexture->mBindIndex == -1) { return; } FBuffer *aPositionsBuffer = gBufferCache.GetArrayBuffer(sizeof(float) * pCount * 3); FBuffer *aTextureCoordsBuffer = gBufferCache.GetArrayBuffer(sizeof(float) * pCount * 3); FBuffer *aNormalsBuffer = gBufferCache.GetArrayBuffer(sizeof(float) * pCount * 3); if (aPositionsBuffer != NULL && aTextureCoordsBuffer != NULL && aNormalsBuffer != NULL) {\\ if (aPositionsBuffer->mBindIndex != -1 && aTextureCoordsBuffer->mBindIndex != -1 && aNormalsBuffer->mBindIndex != -1) { BufferArrayWrite(aPositionsBuffer, pPositions, sizeof(float) * pCount * 3); ArrayBufferPositions(aPositionsBuffer); BufferArrayWrite(aTextureCoordsBuffer, pTextureCoords, sizeof(float) * pCount * 3); ArrayBufferTextureCoords(aTextureCoordsBuffer); BufferArrayWrite(aNormalsBuffer, pTextureCoords, sizeof(float) * pCount * 3); ArrayBufferNormals(aNormalsBuffer); TextureBind(pTexture); DrawTriangles(pCount); } } } void Graphics::DrawTriangles(int pCount, float *pPositions, float *pTextureCoords, float *pNormals) { } void Graphics::DrawTriangles(int pCount) { glDrawArrays(GL_TRIANGLES, 0, pCount); } void Graphics::DrawTriangleStrips(int pCount) { glDrawArrays(GL_TRIANGLE_STRIP, 0, pCount); } void Graphics::DrawTrianglesIndexed(GFX_MODEL_INDEX_TYPE *pIndices, int pCount) { glDrawElements(GL_TRIANGLES, pCount, GFX_MODEL_INDEX_GL_TYPE, pIndices); } void Graphics::DrawTrianglesIndexedWithPackedBuffers(FBuffer *pVertexBuffer, int pVertexBufferOffset, GFX_MODEL_INDEX_TYPE *pIndices, int pCount, FTexture *pTexture) { if (pVertexBuffer == NULL || pVertexBuffer->mBindIndex == -1) { return; } Graphics::TextureBind(pTexture); Graphics::ArrayBufferData(pVertexBuffer, pVertexBufferOffset); Graphics::ArrayBufferPositions(NULL, 0); Graphics::ArrayBufferTextureCoords(NULL, sizeof(float) * 3); Graphics::ArrayBufferNormals(NULL, sizeof(float) * 6); Graphics::DrawTrianglesIndexed(pIndices, pCount); } void Graphics::DrawTriangleStripsIndexed(GFX_MODEL_INDEX_TYPE *pIndices, int pCount) { glDrawElements(GL_TRIANGLE_STRIP, pCount, GFX_MODEL_INDEX_GL_TYPE, pIndices); } void Graphics::MatrixProjectionSet(FMatrix &pMatrix) { cMatrixProjection.Set(pMatrix); } void Graphics::MatrixModelViewSet(FMatrix &pMatrix) { cMatrixModelView.Set(pMatrix); } void Graphics::MatrixProjectionReset() { cMatrixProjection.Reset(); } void Graphics::MatrixModelViewReset() { cMatrixModelView.Reset(); } void Graphics::MatrixProjectionResetOrtho() { Graphics::MatrixProjectionSet(cMatrixOrtho); } FMatrix Graphics::MatrixProjectionGet() { FMatrix aResult; aResult.Set(cMatrixProjection); return aResult; } void Graphics::MatrixProjectionGet(FMatrix *pMatrix) { pMatrix->Set(cMatrixProjection); } FMatrix Graphics::MatrixModelViewGet() { FMatrix aResult; aResult.Set(cMatrixModelView); return aResult; } void Graphics::MatrixModelViewGet(FMatrix *pMatrix) { pMatrix->Set(cMatrixModelView); } void Graphics::CullFacesSetFront() { glEnable(GL_CULL_FACE); //glCullFace(GL_FRONT); glCullFace(GL_BACK); } void Graphics::CullFacesSetBack() { glEnable(GL_CULL_FACE); //glCullFace(GL_BACK); glCullFace(GL_FRONT); } void Graphics::CullFacesSetDisabled() { glDisable(GL_CULL_FACE); } void Graphics::RenderQuad(float pX1, float pY1, float pX2, float pY2, float pX3, float pY3, float pX4, float pY4, FTexture *pTexture) { RenderQuad(pX1, pY1, pX2, pY2, pX3, pY3, pX4, pY4, 0, 0, 0, 1, 1, 0, 1, 1, pTexture); } static float cRenderQuadBufferPositions[9]; static float cRenderQuadBufferUV[9]; void Graphics::RenderQuad(float pX1, float pY1, float pX2, float pY2, float pX3, float pY3, float pX4, float pY4, float pU1, float pV1, float pU2, float pV2, float pU3, float pV3, float pU4, float pV4, FTexture *pTexture) { cRenderQuadBufferPositions[0] = pX1; cRenderQuadBufferPositions[1] = pY1; cRenderQuadBufferPositions[2] = pX2; cRenderQuadBufferPositions[3] = pY2; cRenderQuadBufferPositions[4] = pX3; cRenderQuadBufferPositions[5] = pY3; cRenderQuadBufferPositions[6] = pX4; cRenderQuadBufferPositions[7] = pY4; cRenderQuadBufferUV[0] = pU1; cRenderQuadBufferUV[1] = pV1; cRenderQuadBufferUV[2] = pU2; cRenderQuadBufferUV[3] = pV2; cRenderQuadBufferUV[4] = pU3; cRenderQuadBufferUV[5] = pV3; cRenderQuadBufferUV[6] = pU4; cRenderQuadBufferUV[7] = pV4; DrawSprite(cRenderQuadBufferPositions, cRenderQuadBufferUV, pTexture); } //void Graphics::RenderQuadPushed(float pX1, float pY1, float pX2, float pY2, float pX3, float pY3, float pX4, float pY4, //float pU1, float pV1, float pU2, float pV2, float pU3, float pV3, float pU4, //float pV4, FTexture *pTexture, float pPush) void Graphics::RenderQuadScaled(float pX1, float pY1, float pX2, float pY2, float pX3, float pY3, float pX4, float pY4, float pU1, float pV1, float pU2, float pV2, float pU3, float pV3, float pU4, float pV4, FTexture *pTexture, float pScale) { float aRangeX = (pX2 - pX1); float aRangeY = (pY3 - pY1); float aCenterX = pX1 + aRangeX / 2.0f; float aCenterY = pY1 + aRangeY / 2.0f; aRangeX *= pScale; aRangeY *= pScale; aRangeX /= 2.0f; aRangeY /= 2.0f; pX1 = aCenterX - aRangeX; pX2 = aCenterX + aRangeX; pY1 = aCenterY - aRangeY; pY3 = aCenterY + aRangeY; pX3 = pX1; pX4 = pX2; pY2 = pY1; pY4 = pY3; cRenderQuadBufferPositions[0] = pX1; cRenderQuadBufferPositions[1] = pY1; cRenderQuadBufferPositions[2] = pX2; cRenderQuadBufferPositions[3] = pY2; cRenderQuadBufferPositions[4] = pX3; cRenderQuadBufferPositions[5] = pY3; cRenderQuadBufferPositions[6] = pX4; cRenderQuadBufferPositions[7] = pY4; cRenderQuadBufferUV[0] = pU1; cRenderQuadBufferUV[1] = pV1; cRenderQuadBufferUV[2] = pU2; cRenderQuadBufferUV[3] = pV2; cRenderQuadBufferUV[4] = pU3; cRenderQuadBufferUV[5] = pV3; cRenderQuadBufferUV[6] = pU4; cRenderQuadBufferUV[7] = pV4; DrawSprite(cRenderQuadBufferPositions, cRenderQuadBufferUV, pTexture); } void Graphics::RenderQuadScaled(float pX1, float pY1, float pX2, float pY2, float pX3, float pY3, float pX4, float pY4, float pU1, float pV1, float pU2, float pV2, float pU3, float pV3, float pU4, float pV4, FTexture *pTexture, float pScale, float pCenterX, float pCenterY) { pX1 = pCenterX - (pCenterX - pX1) * pScale; pX2 = pCenterX - (pX2 - pCenterX) * pScale; pY1 = pCenterY - (pCenterY - pY1) * pScale; pY3 = pCenterY - (pY2 - pCenterY) * pScale; pX3 = pX1; pX4 = pX2; pY2 = pY1; pY4 = pY3; //pX1 -= pPush; //pX2 += pPush; cRenderQuadBufferPositions[0] = pX1; cRenderQuadBufferPositions[1] = pY1; cRenderQuadBufferPositions[2] = pX2; cRenderQuadBufferPositions[3] = pY2; cRenderQuadBufferPositions[4] = pX3; cRenderQuadBufferPositions[5] = pY3; cRenderQuadBufferPositions[6] = pX4; cRenderQuadBufferPositions[7] = pY4; cRenderQuadBufferUV[0] = pU1; cRenderQuadBufferUV[1] = pV1; cRenderQuadBufferUV[2] = pU2; cRenderQuadBufferUV[3] = pV2; cRenderQuadBufferUV[4] = pU3; cRenderQuadBufferUV[5] = pV3; cRenderQuadBufferUV[6] = pU4; cRenderQuadBufferUV[7] = pV4; DrawSprite(cRenderQuadBufferPositions, cRenderQuadBufferUV, pTexture); } void Graphics::RenderTriangle(float pX1, float pY1, float pZ1, float pX2, float pY2, float pZ2, float pX3, float pY3, float pZ3) { cRenderQuadBufferPositions[0] = pX1; cRenderQuadBufferPositions[1] = pY1; cRenderQuadBufferPositions[2] = pZ1; cRenderQuadBufferPositions[3] = pX2; cRenderQuadBufferPositions[4] = pY2; cRenderQuadBufferPositions[5] = pZ2; cRenderQuadBufferPositions[6] = pX3; cRenderQuadBufferPositions[7] = pY3; cRenderQuadBufferPositions[8] = pZ3; } void Graphics::RenderTriangle(float pX1, float pY1, float pX2, float pY2, float pX3, float pY3) { RenderTriangle(pX1, pY1, 0.0f, pX2, pY2, 0.0f, pX3, pY3, 0.0f); } bool Graphics::DrawSpriteSetup(float *pPositions, float *pTextureCoords) { //gQuadBufferPosition = Graphics::BufferArrayGenerate(sizeof(float) * 4); //gQuadBufferTextureCoord = Graphics::BufferArrayGenerate(sizeof(float) * 4); FBuffer *aBufferPositions = gBufferCache.GetArrayBuffer(sizeof(float) * 8); if (aBufferPositions == NULL) { return false; } if (aBufferPositions->mBindIndex == -1) { return false; } FBuffer *aBufferTextureCoords = gBufferCache.GetArrayBuffer(sizeof(float) * 8); if (aBufferTextureCoords == NULL) { return false; } if (aBufferTextureCoords->mBindIndex == -1) { return false; } BufferArrayWrite(aBufferPositions, pPositions, sizeof(float) * 8); ArrayBufferPositions(aBufferPositions); BufferArrayWrite(aBufferTextureCoords, pTextureCoords, sizeof(float) * 8); ArrayBufferTextureCoords(aBufferTextureCoords); return true; } void Graphics::DrawSprite(float *pPositions, float *pTextureCoords, FTexture *pTexture) { if (pTexture == NULL || pTexture->mBindIndex == -1) { return; } if (DrawSpriteSetup(pPositions, pTextureCoords)) { TextureBind(pTexture); UniformBind(); // DrawTriangleStrips(4); } } void Graphics::DrawSprite(float pX, float pY, float pScaleX, float pScaleY, float pScaleZ, float pRotation, float *pPositions, float *pTextureCoords, FTexture *pTexture) { FMatrix aHold = cMatrixModelView; FMatrix aModelView = cMatrixModelView; if (pX != 0.0f || pY != 0.0f) { aModelView.Translate(pX, pY); } if (pScaleX != 1.0f || pScaleY != 1.0f || pScaleZ != 1.0f) { aModelView.Scale(pScaleX, pScaleY, pScaleZ); } if (pRotation != 0.0f) { aModelView.Rotate(pRotation); } MatrixModelViewSet(aModelView); DrawSprite(pPositions, pTextureCoords, pTexture); MatrixModelViewSet(aHold); } void Graphics::DrawSpriteTriangle(float pX, float pY, float pScaleX, float pScaleY, float pScaleZ, float pRotation, float *pPositions, float *pTextureCoords, FTexture *pTexture) { FMatrix aHold = cMatrixModelView; FMatrix aModelView = cMatrixModelView; aModelView.Translate(pX, pY); aModelView.Scale(pScaleX, pScaleY, pScaleZ); aModelView.Rotate(pRotation); MatrixModelViewSet(aModelView); DrawSpriteTriangle(pPositions, pTextureCoords, pTexture); MatrixModelViewSet(aHold); } bool Graphics::DrawSpriteTriangleSetup(float *pPositions, float *pTextureCoords) { FBuffer *aBufferPositions = gBufferCache.GetArrayBuffer(sizeof(float) * 6); if (aBufferPositions == NULL) { return false; } if (aBufferPositions->mBindIndex == -1) { return false; } FBuffer *aBufferTextureCoords = gBufferCache.GetArrayBuffer(sizeof(float) * 6); if (aBufferTextureCoords == NULL) { return false; } if (aBufferTextureCoords->mBindIndex == -1) { return false; } BufferArrayWrite(aBufferPositions, pPositions, sizeof(float) * 6); ArrayBufferPositions(aBufferPositions); BufferArrayWrite(aBufferTextureCoords, pTextureCoords, sizeof(float) * 6); ArrayBufferTextureCoords(aBufferTextureCoords); return true; /* cVertexCache.Get(sizeof(float) * 6); if (cVertexCache.mResult.mSuccess) { FBuffer *aPositionsBuffer = cVertexCache.mResult.mBuffer; int aPositionsBufferOffset = cVertexCache.mResult.mBufferOffset; BufferArrayWrite(aPositionsBuffer, pPositions, aPositionsBufferOffset, sizeof(float) * 6); ArrayBufferPositions(aPositionsBuffer, aPositionsBufferOffset); } // cVertexCache.Get(sizeof(float) * 6); if (cVertexCache.mResult.mSuccess) { FBuffer *aTextureCoordsBuffer = cVertexCache.mResult.mBuffer; int aTextureCoordsBufferOffset = cVertexCache.mResult.mBufferOffset; BufferArrayWrite(aTextureCoordsBuffer, pTextureCoords, aTextureCoordsBufferOffset, sizeof(float) * 6); ArrayBufferTextureCoords(aTextureCoordsBuffer, aTextureCoordsBufferOffset); } */ } void Graphics::DrawSpriteTriangle(float *pPositions, float *pTextureCoords, FTexture *pTexture) { if (pTexture == NULL || pTexture->mBindIndex == -1) { return; } if (DrawSpriteTriangleSetup(pPositions, pTextureCoords)) { TextureBind(pTexture); UniformBind(); // DrawTriangleStrips(3); } } void Graphics::DrawCurrentTile() { PipelineStateSetSpriteNoBlending(); if (DrawSpriteSetup(cTileRect.mPositions, cTileRect.mTextureCoords)) { MatrixProjectionResetOrtho(); MatrixModelViewReset(); UniformBind(); DrawTriangleStrips(4); } /* cTileRect.SetRect(0.0f, 0.0f, gDeviceWidth2, gDeviceHeight2); UniformBind(); DrawSpriteSetup(cTileRect.mVertex, cTileRect.mTextureCoord); DrawTriangleStrips(4); cTileRect.SetRect(gDeviceWidth2, 0.0f, gDeviceWidth2, gDeviceHeight2); UniformBind(); DrawSpriteSetup(cTileRect.mVertex, cTileRect.mTextureCoord); DrawTriangleStrips(4); cTileRect.SetRect(0.0f, gDeviceHeight2, gDeviceWidth2, gDeviceHeight2); UniformBind(); DrawSpriteSetup(cTileRect.mVertex, cTileRect.mTextureCoord); DrawTriangleStrips(4); cTileRect.SetRect(gDeviceWidth2, gDeviceHeight2, gDeviceWidth2, gDeviceHeight2); UniformBind(); DrawSpriteSetup(cTileRect.mVertex, cTileRect.mTextureCoord); DrawTriangleStrips(4); */ } void Graphics::Ortho2D(float pLeft, float pRight, float pBottom, float pTop) { //glOrthof(pLeft, pRight, pBottom, pTop, -1024.0f, 1024.0f); //glOrthof } void Graphics::Ortho2D() { //Ortho2D(0.0f, 0.0f, gDeviceWidth, gDeviceHeight); } void Graphics::PipelineStateSetShape2DNoBlending() { if (gOpenGLEngine) { BlendDisable(); gOpenGLEngine->UseProgramShape2D(); } } void Graphics::PipelineStateSetShape2DAlphaBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetAlpha(); gOpenGLEngine->UseProgramShape2D(); } } void Graphics::PipelineStateSetShape2DAdditiveBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetAdditive(); gOpenGLEngine->UseProgramShape2D(); } } void Graphics::PipelineStateSetShape3DNoBlending() { if (gOpenGLEngine) { BlendDisable(); gOpenGLEngine->UseProgramShape3D(); } } void Graphics::PipelineStateSetShape3DAlphaBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetAlpha(); gOpenGLEngine->UseProgramShape3D(); } } void Graphics::PipelineStateSetShape3DAdditiveBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetAdditive(); gOpenGLEngine->UseProgramShape3D(); } } void Graphics::PipelineStateSetSpriteNoBlending() { if (gOpenGLEngine) { BlendDisable(); gOpenGLEngine->UseProgramSprite(); } } void Graphics::PipelineStateSetSpriteAlphaBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetAlpha(); gOpenGLEngine->UseProgramSprite(); } } void Graphics::PipelineStateSetSpriteAdditiveBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetAdditive(); gOpenGLEngine->UseProgramSprite(); } } void Graphics::PipelineStateSetSpritePremultipliedBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetPremultiplied(); gOpenGLEngine->UseProgramSprite(); } } void Graphics::PipelineStateSetSpriteWhiteBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetAlpha(); gOpenGLEngine->UseProgramSpriteWhite(); } } void Graphics::PipelineStateSetShapeNodeNoBlending() { if (gOpenGLEngine) { BlendDisable(); gOpenGLEngine->UseProgramShapeNode(); } } void Graphics::PipelineStateSetShapeNodeAlphaBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetAlpha(); gOpenGLEngine->UseProgramShapeNode(); } } void Graphics::PipelineStateSetShapeNodeAdditiveBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetAdditive(); gOpenGLEngine->UseProgramShapeNode(); } } void Graphics::PipelineStateSetShapeNodeSpriteNoBlending() { if (gOpenGLEngine) { BlendDisable(); gOpenGLEngine->UseProgramShapeNodeSprite(); } } void Graphics::PipelineStateSetShapeNodeSpriteAlphaBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetAlpha(); gOpenGLEngine->UseProgramShapeNodeSprite(); } } void Graphics::PipelineStateSetShapeNodeSpriteAdditiveBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetAdditive(); gOpenGLEngine->UseProgramShapeNodeSprite(); } } void Graphics::PipelineStateSetShapeNodeSpritePremultipliedBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetPremultiplied(); gOpenGLEngine->UseProgramShapeNodeSprite(); } } void Graphics::PipelineStateSetSimpleModelNoBlending() { if (gOpenGLEngine) { BlendDisable(); gOpenGLEngine->UseProgramSimpleModel(); } } void Graphics::PipelineStateSetSimpleModelAlphaBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetAlpha(); gOpenGLEngine->UseProgramSimpleModel(); } } void Graphics::PipelineStateSetSimpleModelAdditiveBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetAdditive(); gOpenGLEngine->UseProgramSimpleModel(); } } void Graphics::PipelineStateSetSimpleModelPremultipliedBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetPremultiplied(); gOpenGLEngine->UseProgramSimpleModel(); } } void Graphics::PipelineStateSetSimpleModelIndexedNoBlending() { if (gOpenGLEngine) { BlendDisable(); gOpenGLEngine->UseProgramSimpleModelIndexed(); } } void Graphics::PipelineStateSetSimpleModelIndexedAlphaBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetAlpha(); gOpenGLEngine->UseProgramSimpleModelIndexed(); } } void Graphics::PipelineStateSetModelIndexedNoBlending() { if (gOpenGLEngine) { BlendDisable(); gOpenGLEngine->UseProgramModelIndexed(); } } void Graphics::PipelineStateSetModelIndexedAlphaBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetAlpha(); gOpenGLEngine->UseProgramModelIndexed(); } } void Graphics::PipelineStateSetModelIndexedLightedAmbientNoBlending() { if (gOpenGLEngine) { BlendDisable(); gOpenGLEngine->UseProgramModelIndexedAmbient(); } } void Graphics::PipelineStateSetModelIndexedLightedAmbientAlphaBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetAlpha(); gOpenGLEngine->UseProgramModelIndexedAmbient(); } } void Graphics::PipelineStateSetModelIndexedLightedDiffuseNoBlending() { if (gOpenGLEngine) { BlendDisable(); gOpenGLEngine->UseProgramModelIndexedDiffuse(); } } void Graphics::PipelineStateSetModelIndexedLightedDiffuseAlphaBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetAlpha(); gOpenGLEngine->UseProgramModelIndexedDiffuse(); } } void Graphics::PipelineStateSetModelIndexedLightedPhongNoBlending() { if (gOpenGLEngine) { BlendDisable(); gOpenGLEngine->UseProgramModelIndexedPhong(); } } void Graphics::PipelineStateSetModelIndexedLightedPhongAlphaBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetAlpha(); gOpenGLEngine->UseProgramModelIndexedPhong(); } } void Graphics::PipelineStateSetModelIndexedLightedPhongOverlayNoBlending() { if (gOpenGLEngine) { BlendDisable(); gOpenGLEngine->UseProgramModelIndexedPhongOverlay(); } } void Graphics::PipelineStateSetModelIndexedLightedPhongOverlayAlphaBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetAlpha(); gOpenGLEngine->UseProgramModelIndexedPhongOverlay(); } } void Graphics::PipelineStateSetModelIndexedLightedSimpleSpotlightNoBlending() { if (gOpenGLEngine) { BlendDisable(); gOpenGLEngine->UseProgramModelIndexedSimpleSpotlight(); } } void Graphics::PipelineStateSetModelIndexedLightedSimpleSpotlightAlphaBlending() { if (gOpenGLEngine) { BlendEnable(); BlendSetAlpha(); gOpenGLEngine->UseProgramModelIndexedSimpleSpotlight(); } } int Graphics::RenderPass() { return cCurrentRenderPass; } void Graphics::RenderPassBegin(int pRenderPass, bool pClearColor, bool pClearDepth) { cCurrentRenderPass = pRenderPass; if (pClearDepth) { Graphics::DepthClear(); } if (pClearColor) { //Graphics::Clear(0.025f, 0.025f, 0.065f); Graphics::Clear(0.65f, 0.675f, 0.965f); } //[gMetalEngine startRenderPass:pRenderPass clearingColor: pClearColor clearingDepth: pClearDepth]; } void Graphics::SetShaderProgram(ShaderProgram *pShaderProgram) { cShaderProgram = pShaderProgram; } void Graphics::BlendEnable() { glEnable(GL_BLEND); } void Graphics::BlendDisable() { glDisable(GL_BLEND); } void Graphics::BlendSetAlpha() { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } void Graphics::BlendSetAdditive() { glBlendFunc(GL_SRC_ALPHA, GL_ONE); } void Graphics::BlendSetPremultiplied() { glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } ",16318,True,3144.314209815705,median "/* * Copyright (c) 2016, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file includes definitions for MLE functionality required by the Thread Child, Router, and Leader roles. */ #ifndef MLE_HPP_ #define MLE_HPP_ #include ""openthread-core-config.h"" #include ""common/encoding.hpp"" #include ""common/locator.hpp"" #include ""common/non_copyable.hpp"" #include ""common/timer.hpp"" #include ""mac/mac.hpp"" #include ""meshcop/joiner_router.hpp"" #include ""meshcop/meshcop.hpp"" #include ""net/udp6.hpp"" #include ""thread/link_metrics.hpp"" #include ""thread/link_metrics_tlvs.hpp"" #include ""thread/mle_tlvs.hpp"" #include ""thread/mle_types.hpp"" #include ""thread/neighbor_table.hpp"" #include ""thread/topology.hpp"" namespace ot { /** * @addtogroup core-mle MLE * * @brief * This module includes definitions for the MLE protocol. * * @{ * * @defgroup core-mle-core Core * @defgroup core-mle-router Router * @defgroup core-mle-tlvs TLVs * * @} */ /** * @namespace ot::Mle * * @brief * This namespace includes definitions for the MLE protocol. */ namespace Mle { /** * @addtogroup core-mle-core * * @brief * This module includes definitions for MLE functionality required by the Thread Child, Router, and Leader roles. * * @{ * */ /** * This class implements MLE functionality required by the Thread EndDevices, Router, and Leader roles. * */ class Mle : public InstanceLocator, private NonCopyable { friend class DiscoverScanner; friend class ot::Notifier; #if OPENTHREAD_CONFIG_MLE_LINK_METRICS_ENABLE friend class ot::LinkMetrics; #endif public: /** * This constructor initializes the MLE object. * * @param[in] aInstance A reference to the OpenThread instance. * */ explicit Mle(Instance &aInstance); /** * This method enables MLE. * * @retval kErrorNone Successfully enabled MLE. * @retval kErrorAlready MLE was already enabled. * */ Error Enable(void); /** * This method disables MLE. * * @retval kErrorNone Successfully disabled MLE. * */ Error Disable(void); /** * This method starts the MLE protocol operation. * * @param[in] aAnnounceAttach True if attach on the announced thread network with newer active timestamp, * or False if not. * * @retval kErrorNone Successfully started the protocol operation. * @retval kErrorAlready The protocol operation was already started. * */ Error Start(bool aAnnounceAttach); /** * This method stops the MLE protocol operation. * * @param[in] aClearNetworkDatasets True to clear network datasets, False not. * */ void Stop(bool aClearNetworkDatasets); /** * This method restores network information from non-volatile memory. * * @retval kErrorNone Successfully restore the network information. * @retval kErrorNotFound There is no valid network information stored in non-volatile memory. * */ Error Restore(void); /** * This method stores network information into non-volatile memory. * * @retval kErrorNone Successfully store the network information. * @retval kErrorNoBufs Could not store the network information due to insufficient memory space. * */ Error Store(void); /** * This method generates an MLE Announce message. * * @param[in] aChannel The channel to use when transmitting. * @param[in] aOrphanAnnounce To indicate if MLE Announce is sent from an orphan end device. * */ void SendAnnounce(uint8_t aChannel, bool aOrphanAnnounce); /** * This method causes the Thread interface to detach from the Thread network. * * @retval kErrorNone Successfully detached from the Thread network. * @retval kErrorInvalidState MLE is Disabled. * */ Error BecomeDetached(void); /** * This method causes the Thread interface to attempt an MLE attach. * * @param[in] aMode Indicates what partitions to attach to. * * @retval kErrorNone Successfully began the attach process. * @retval kErrorInvalidState MLE is Disabled. * @retval kErrorBusy An attach process is in progress. * */ Error BecomeChild(AttachMode aMode); /** * This method indicates whether or not the Thread device is attached to a Thread network. * * @retval TRUE Attached to a Thread network. * @retval FALSE Not attached to a Thread network. * */ bool IsAttached(void) const; /** * This method indicates whether device is currently attaching or not. * * Note that an already attached device may also be in attaching state. Examples of this include a leader/router * trying to attach to a better partition, or a child trying to find a better parent (when feature * `OPENTHREAD_CONFIG_PARENT_SEARCH_ENABLE` is enabled). * * @retval TRUE Device is currently trying to attach. * @retval FALSE Device is not in middle of attach process. * */ bool IsAttaching(void) const { return (mAttachState != kAttachStateIdle); } /** * This method returns the current Thread device role. * * @returns The current Thread device role. * */ DeviceRole GetRole(void) const { return mRole; } /** * This method indicates whether device role is disabled. * * @retval TRUE Device role is disabled. * @retval FALSE Device role is not disabled. * */ bool IsDisabled(void) const { return (mRole == kRoleDisabled); } /** * This method indicates whether device role is detached. * * @retval TRUE Device role is detached. * @retval FALSE Device role is not detached. * */ bool IsDetached(void) const { return (mRole == kRoleDetached); } /** * This method indicates whether device role is child. * * @retval TRUE Device role is child. * @retval FALSE Device role is not child. * */ bool IsChild(void) const { return (mRole == kRoleChild); } /** * This method indicates whether device role is router. * * @retval TRUE Device role is router. * @retval FALSE Device role is not router. * */ bool IsRouter(void) const { return (mRole == kRoleRouter); } /** * This method indicates whether device role is leader. * * @retval TRUE Device role is leader. * @retval FALSE Device role is not leader. * */ bool IsLeader(void) const { return (mRole == kRoleLeader); } /** * This method indicates whether device role is either router or leader. * * @retval TRUE Device role is either router or leader. * @retval FALSE Device role is neither router nor leader. * */ bool IsRouterOrLeader(void) const; /** * This method returns the Device Mode as reported in the Mode TLV. * * @returns The Device Mode as reported in the Mode TLV. * */ DeviceMode GetDeviceMode(void) const { return mDeviceMode; } /** * This method sets the Device Mode as reported in the Mode TLV. * * @param[in] aDeviceMode The device mode to set. * * @retval kErrorNone Successfully set the Mode TLV. * @retval kErrorInvalidArgs The mode combination specified in @p aMode is invalid. * */ Error SetDeviceMode(DeviceMode aDeviceMode); /** * This method indicates whether or not the device is rx-on-when-idle. * * @returns TRUE if rx-on-when-idle, FALSE otherwise. * */ bool IsRxOnWhenIdle(void) const { return mDeviceMode.IsRxOnWhenIdle(); } /** * This method indicates whether or not the device is a Full Thread Device. * * @returns TRUE if a Full Thread Device, FALSE otherwise. * */ bool IsFullThreadDevice(void) const { return mDeviceMode.IsFullThreadDevice(); } /** * This method indicates whether or not the device requests Full Network Data. * * @returns TRUE if requests Full Network Data, FALSE otherwise. * */ bool IsFullNetworkData(void) const { return mDeviceMode.IsFullNetworkData(); } /** * This method indicates whether or not the device is a Minimal End Device. * * @returns TRUE if the device is a Minimal End Device, FALSE otherwise. * */ bool IsMinimalEndDevice(void) const { return mDeviceMode.IsMinimalEndDevice(); } /** * This method returns a pointer to the Mesh Local Prefix. * * @returns A reference to the Mesh Local Prefix. * */ const MeshLocalPrefix &GetMeshLocalPrefix(void) const { return static_cast(mMeshLocal16.GetAddress().GetPrefix()); } /** * This method sets the Mesh Local Prefix. * * @param[in] aMeshLocalPrefix A reference to the Mesh Local Prefix. * */ void SetMeshLocalPrefix(const MeshLocalPrefix &aMeshLocalPrefix); /** * This method applies the Mesh Local Prefix. * */ void ApplyMeshLocalPrefix(void); /** * This method returns a reference to the Thread link-local address. * * The Thread link local address is derived using IEEE802.15.4 Extended Address as Interface Identifier. * * @returns A reference to the Thread link local address. * */ const Ip6::Address &GetLinkLocalAddress(void) const { return mLinkLocal64.GetAddress(); } /** * This method updates the link local address. * * Call this method when the IEEE 802.15.4 Extended Address has changed. * */ void UpdateLinkLocalAddress(void); /** * This method returns a reference to the link-local all Thread nodes multicast address. * * @returns A reference to the link-local all Thread nodes multicast address. * */ const Ip6::Address &GetLinkLocalAllThreadNodesAddress(void) const { return mLinkLocalAllThreadNodes.GetAddress(); } /** * This method returns a reference to the realm-local all Thread nodes multicast address. * * @returns A reference to the realm-local all Thread nodes multicast address. * */ const Ip6::Address &GetRealmLocalAllThreadNodesAddress(void) const { return mRealmLocalAllThreadNodes.GetAddress(); } /** * This method gets the parent when operating in End Device mode. * * @returns A reference to the parent. * */ Router &GetParent(void) { return mParent; } /** * This method get the parent candidate. * * The parent candidate is valid when attempting to attach to a new parent. * */ Router &GetParentCandidate(void) { return mParentCandidate; } /** * This method indicates whether or not an IPv6 address is an RLOC. * * @retval TRUE If @p aAddress is an RLOC. * @retval FALSE If @p aAddress is not an RLOC. * */ bool IsRoutingLocator(const Ip6::Address &aAddress) const; /** * This method indicates whether or not an IPv6 address is an ALOC. * * @retval TRUE If @p aAddress is an ALOC. * @retval FALSE If @p aAddress is not an ALOC. * */ bool IsAnycastLocator(const Ip6::Address &aAddress) const; /** * This method indicates whether or not an IPv6 address is a Mesh Local Address. * * @retval TRUE If @p aAddress is a Mesh Local Address. * @retval FALSE If @p aAddress is not a Mesh Local Address. * */ bool IsMeshLocalAddress(const Ip6::Address &aAddress) const; /** * This method returns the MLE Timeout value. * * @returns The MLE Timeout value in seconds. * */ uint32_t GetTimeout(void) const { return mTimeout; } /** * This method sets the MLE Timeout value. * * @param[in] aTimeout The Timeout value in seconds. * */ void SetTimeout(uint32_t aTimeout); /** * This method returns the RLOC16 assigned to the Thread interface. * * @returns The RLOC16 assigned to the Thread interface. * */ uint16_t GetRloc16(void) const; /** * This method returns a reference to the RLOC assigned to the Thread interface. * * @returns A reference to the RLOC assigned to the Thread interface. * */ const Ip6::Address &GetMeshLocal16(void) const { return mMeshLocal16.GetAddress(); } /** * This method returns a reference to the ML-EID assigned to the Thread interface. * * @returns A reference to the ML-EID assigned to the Thread interface. * */ const Ip6::Address &GetMeshLocal64(void) const { return mMeshLocal64.GetAddress(); } /** * This method returns the Router ID of the Leader. * * @returns The Router ID of the Leader. * */ uint8_t GetLeaderId(void) const { return mLeaderData.GetLeaderRouterId(); } /** * This method retrieves the Leader's RLOC. * * @param[out] aAddress A reference to the Leader's RLOC. * * @retval kErrorNone Successfully retrieved the Leader's RLOC. * @retval kErrorDetached The Thread interface is not currently attached to a Thread Partition. * */ Error GetLeaderAddress(Ip6::Address &aAddress) const; /** * This method retrieves the Leader's ALOC. * * @param[out] aAddress A reference to the Leader's ALOC. * * @retval kErrorNone Successfully retrieved the Leader's ALOC. * @retval kErrorDetached The Thread interface is not currently attached to a Thread Partition. * */ Error GetLeaderAloc(Ip6::Address &aAddress) const { return GetLocatorAddress(aAddress, kAloc16Leader); } /** * This method computes the Commissioner's ALOC. * * @param[out] aAddress A reference to the Commissioner's ALOC. * @param[in] aSessionId Commissioner session id. * * @retval kErrorNone Successfully retrieved the Commissioner's ALOC. * @retval kErrorDetached The Thread interface is not currently attached to a Thread Partition. * */ Error GetCommissionerAloc(Ip6::Address &aAddress, uint16_t aSessionId) const { return GetLocatorAddress(aAddress, CommissionerAloc16FromId(aSessionId)); } /** * This method retrieves the Service ALOC for given Service ID. * * @param[in] aServiceId Service ID to get ALOC for. * @param[out] aAddress A reference to the Service ALOC. * * @retval kErrorNone Successfully retrieved the Service ALOC. * @retval kErrorDetached The Thread interface is not currently attached to a Thread Partition. * */ Error GetServiceAloc(uint8_t aServiceId, Ip6::Address &aAddress) const; /** * This method returns the most recently received Leader Data. * * @returns A reference to the most recently received Leader Data. * */ const LeaderData &GetLeaderData(void); /** * This method derives the Child ID from a given RLOC16. * * @param[in] aRloc16 The RLOC16 value. * * @returns The Child ID portion of an RLOC16. * */ static uint16_t ChildIdFromRloc16(uint16_t aRloc16) { return aRloc16 & kMaxChildId; } /** * This method derives the Router ID portion from a given RLOC16. * * @param[in] aRloc16 The RLOC16 value. * * @returns The Router ID portion of an RLOC16. * */ static uint8_t RouterIdFromRloc16(uint16_t aRloc16) { return aRloc16 >> kRouterIdOffset; } /** * This method returns whether the two RLOC16 have the same Router ID. * * @param[in] aRloc16A The first RLOC16 value. * @param[in] aRloc16B The second RLOC16 value. * * @returns true if the two RLOC16 have the same Router ID, false otherwise. * */ static bool RouterIdMatch(uint16_t aRloc16A, uint16_t aRloc16B) { return RouterIdFromRloc16(aRloc16A) == RouterIdFromRloc16(aRloc16B); } /** * This method returns the Service ID corresponding to a Service ALOC16. * * @param[in] aAloc16 The Servicer ALOC16 value. * * @returns The Service ID corresponding to given ALOC16. * */ static uint8_t ServiceIdFromAloc(uint16_t aAloc16) { return static_cast(aAloc16 - kAloc16ServiceStart); } /** * This method returns the Service Aloc corresponding to a Service ID. * * @param[in] aServiceId The Service ID value. * * @returns The Service ALOC16 corresponding to given ID. * */ static uint16_t ServiceAlocFromId(uint8_t aServiceId) { return static_cast(aServiceId + kAloc16ServiceStart); } /** * This method returns the Commissioner Aloc corresponding to a Commissioner Session ID. * * @param[in] aSessionId The Commissioner Session ID value. * * @returns The Commissioner ALOC16 corresponding to given ID. * */ static uint16_t CommissionerAloc16FromId(uint16_t aSessionId) { return static_cast((aSessionId & kAloc16CommissionerMask) + kAloc16CommissionerStart); } /** * This method derives RLOC16 from a given Router ID. * * @param[in] aRouterId The Router ID value. * * @returns The RLOC16 corresponding to the given Router ID. * */ static uint16_t Rloc16FromRouterId(uint8_t aRouterId) { return static_cast(aRouterId << kRouterIdOffset); } /** * This method indicates whether or not @p aRloc16 refers to an active router. * * @param[in] aRloc16 The RLOC16 value. * * @retval TRUE If @p aRloc16 refers to an active router. * @retval FALSE If @p aRloc16 does not refer to an active router. * */ static bool IsActiveRouter(uint16_t aRloc16) { return ChildIdFromRloc16(aRloc16) == 0; } /** * This method returns a reference to the send queue. * * @returns A reference to the send queue. * */ const MessageQueue &GetMessageQueue(void) const { return mDelayedResponses; } /** * This method frees multicast MLE Data Response from Delayed Message Queue if any. * */ void RemoveDelayedDataResponseMessage(void); /** * This method converts a device role into a human-readable string. * */ static const char *RoleToString(DeviceRole aRole); /** * This method gets the MLE counters. * * @returns A reference to the MLE counters. * */ const otMleCounters &GetCounters(void) const { return mCounters; } /** * This method resets the MLE counters. * */ void ResetCounters(void) { memset(&mCounters, 0, sizeof(mCounters)); } /** * This function registers the client callback that is called when processing an MLE Parent Response message. * * @param[in] aCallback A pointer to a function that is called to deliver MLE Parent Response data. * @param[in] aContext A pointer to application-specific context. * */ void RegisterParentResponseStatsCallback(otThreadParentResponseCallback aCallback, void *aContext); /** * This method requests MLE layer to prepare and send a shorter version of Child ID Request message by only * including the mesh-local IPv6 address in the Address Registration TLV. * * This method should be called when a previous MLE Child ID Request message would require fragmentation at 6LoWPAN * layer. * */ void RequestShorterChildIdRequest(void); /** * This method gets the RLOC or ALOC of a given RLOC16 or ALOC16. * * @param[out] aAddress A reference to the RLOC or ALOC. * @param[in] aLocator RLOC16 or ALOC16. * * @retval kErrorNone If got the RLOC or ALOC successfully. * @retval kErrorDetached If device is detached. * */ Error GetLocatorAddress(Ip6::Address &aAddress, uint16_t aLocator) const; /** * This method schedules a Child Update Request. * */ void ScheduleChildUpdateRequest(void); /* * This method indicates whether or not the device has restored the network information from * non-volatile settings after boot. * * @retval true Successfully restored the network information. * @retval false No valid network information was found. * */ bool HasRestored(void) const { return mHasRestored; } protected: /** * MLE Command Types. * */ enum Command : uint8_t { kCommandLinkRequest = 0, ///< Link Request kCommandLinkAccept = 1, ///< Link Accept kCommandLinkAcceptAndRequest = 2, ///< Link Accept and Reject kCommandLinkReject = 3, ///< Link Reject kCommandAdvertisement = 4, ///< Advertisement kCommandUpdate = 5, ///< Update kCommandUpdateRequest = 6, ///< Update Request kCommandDataRequest = 7, ///< Data Request kCommandDataResponse = 8, ///< Data Response kCommandParentRequest = 9, ///< Parent Request kCommandParentResponse = 10, ///< Parent Response kCommandChildIdRequest = 11, ///< Child ID Request kCommandChildIdResponse = 12, ///< Child ID Response kCommandChildUpdateRequest = 13, ///< Child Update Request kCommandChildUpdateResponse = 14, ///< Child Update Response kCommandAnnounce = 15, ///< Announce kCommandDiscoveryRequest = 16, ///< Discovery Request kCommandDiscoveryResponse = 17, ///< Discovery Response kCommandLinkMetricsManagementRequest = 18, ///< Link Metrics Management Request kCommandLinkMetricsManagementResponse = 19, ///< Link Metrics Management Response kCommandLinkProbe = 20, ///< Link Probe kCommandTimeSync = 99, ///< Time Sync (applicable when OPENTHREAD_CONFIG_TIME_SYNC_ENABLE enabled) }; /** * States during attach (when searching for a parent). * */ enum AttachState { kAttachStateIdle, ///< Not currently searching for a parent. kAttachStateProcessAnnounce, ///< Waiting to process a received Announce (to switch channel/pan-id). kAttachStateStart, ///< Starting to look for a parent. kAttachStateParentRequestRouter, ///< Searching for a Router to attach to. kAttachStateParentRequestReed, ///< Searching for Routers or REEDs to attach to. kAttachStateAnnounce, ///< Send Announce messages kAttachStateChildIdRequest, ///< Sending a Child ID Request message. }; /** * States when reattaching network using stored dataset * */ enum ReattachState { kReattachStop = 0, ///< Reattach process is disabled or finished kReattachStart = 1, ///< Start reattach process kReattachActive = 2, ///< Reattach using stored Active Dataset kReattachPending = 3, ///< Reattach using stored Pending Dataset }; enum { kMleMaxResponseDelay = 1000u, ///< Maximum delay before responding to a multicast request. }; /** * This enumeration type is used in `AppendAddressRegistration()` to determine which addresses to include in the * appended Address Registration TLV. * */ enum AddressRegistrationMode { kAppendAllAddresses, ///< Append all addresses (unicast/multicast) in Address Registration TLV. kAppendMeshLocalOnly, ///< Only append the Mesh Local (ML-EID) address in Address Registration TLV. }; /** * This enumeration represents the message actions used in `Log()` methods. * */ enum MessageAction : uint8_t { kMessageSend, kMessageReceive, kMessageDelay, kMessageRemoveDelayed, }; /** * This enumeration represents message types used in `Log()` methods. * */ enum MessageType : uint8_t { kTypeAdvertisement, kTypeAnnounce, kTypeChildIdRequest, kTypeChildIdRequestShort, kTypeChildIdResponse, kTypeChildUpdateRequestOfParent, kTypeChildUpdateResponseOfParent, kTypeDataRequest, kTypeDataResponse, kTypeDiscoveryRequest, kTypeDiscoveryResponse, kTypeGenericDelayed, kTypeGenericUdp, kTypeParentRequestToRouters, kTypeParentRequestToRoutersReeds, kTypeParentResponse, #if OPENTHREAD_FTD kTypeAddressRelease, kTypeAddressReleaseReply, kTypeAddressReply, kTypeAddressSolicit, kTypeChildUpdateRequestOfChild, kTypeChildUpdateResponseOfChild, kTypeChildUpdateResponseOfUnknownChild, kTypeLinkAccept, kTypeLinkAcceptAndRequest, kTypeLinkReject, kTypeLinkRequest, kTypeParentRequest, #if OPENTHREAD_CONFIG_TIME_SYNC_ENABLE kTypeTimeSync, #endif #endif #if OPENTHREAD_CONFIG_MLE_LINK_METRICS_ENABLE kTypeLinkMetricsManagementRequest, kTypeLinkMetricsManagementResponse, kTypeLinkProbe, #endif }; /** * This type represents a Challenge (or Response) data. * */ struct Challenge { uint8_t mBuffer[kMaxChallengeSize]; ///< Buffer containing the challenge/response byte sequence. uint8_t mLength; ///< Challenge length (in bytes). /** * This method generates a cryptographically secure random sequence to populate the challenge data. * */ void GenerateRandom(void); /** * This method indicates whether the Challenge matches a given buffer. * * @param[in] aBuffer A pointer to a buffer to compare with the Challenge. * @param[in] aLength Length of @p aBuffer (in bytes). * * @retval TRUE If the Challenge matches the given buffer. * @retval FALSE If the Challenge does not match the given buffer. * */ bool Matches(const uint8_t *aBuffer, uint8_t aLength) const; /** * This method indicates whether two Challenge data byte sequences are equal or not. * * @param[in] aOther Another Challenge data to compare. * * @retval TRUE If the two Challenges match. * @retval FALSE If the two Challenges do not match. * */ bool operator==(const Challenge &aOther) const { return Matches(aOther.mBuffer, aOther.mLength); } }; /** * This type represents list of requested TLVs in a TLV Request TLV. * */ struct RequestedTlvs { enum { kMaxNumTlvs = 16, ///< Maximum number of TLVs in request array. }; uint8_t mTlvs[kMaxNumTlvs]; ///< Array of requested TLVs. uint8_t mNumTlvs; ///< Number of TLVs in the array. }; /** * This method allocates a new message buffer for preparing an MLE message. * * @returns A pointer to the message or nullptr if insufficient message buffers are available. * */ Message *NewMleMessage(void); /** * This method sets the device role. * * @param[in] aRole A device role. * */ void SetRole(DeviceRole aRole); /** * This method sets the attach state * * @param[in] aState An attach state * */ void SetAttachState(AttachState aState); /** * This method appends an MLE header to a message. * * @param[in] aMessage A reference to the message. * @param[in] aCommand The MLE Command Type. * * @retval kErrorNone Successfully appended the header. * @retval kErrorNoBufs Insufficient buffers available to append the header. * */ Error AppendHeader(Message &aMessage, Command aCommand); /** * This method appends a Source Address TLV to a message. * * @param[in] aMessage A reference to the message. * * @retval kErrorNone Successfully appended the Source Address TLV. * @retval kErrorNoBufs Insufficient buffers available to append the Source Address TLV. * */ Error AppendSourceAddress(Message &aMessage) const; /** * This method appends a Mode TLV to a message. * * @param[in] aMessage A reference to the message. * @param[in] aMode The Device Mode. * * @retval kErrorNone Successfully appended the Mode TLV. * @retval kErrorNoBufs Insufficient buffers available to append the Mode TLV. * */ Error AppendMode(Message &aMessage, DeviceMode aMode); /** * This method appends a Timeout TLV to a message. * * @param[in] aMessage A reference to the message. * @param[in] aTimeout The Timeout value. * * @retval kErrorNone Successfully appended the Timeout TLV. * @retval kErrorNoBufs Insufficient buffers available to append the Timeout TLV. * */ Error AppendTimeout(Message &aMessage, uint32_t aTimeout); /** * This method appends a Challenge TLV to a message. * * @param[in] aMessage A reference to the message. * @param[in] aChallenge A pointer to the Challenge value. * @param[in] aChallengeLength The length of the Challenge value in bytes. * * @retval kErrorNone Successfully appended the Challenge TLV. * @retval kErrorNoBufs Insufficient buffers available to append the Challenge TLV. * */ Error AppendChallenge(Message &aMessage, const uint8_t *aChallenge, uint8_t aChallengeLength); /** * This method appends a Challenge TLV to a message. * * @param[in] aMessage A reference to the message. * @param[in] aChallenge A reference to the Challenge data. * * @retval kErrorNone Successfully appended the Challenge TLV. * @retval kErrorNoBufs Insufficient buffers available to append the Challenge TLV. * */ Error AppendChallenge(Message &aMessage, const Challenge &aChallenge); /** * This method reads Challenge TLV from a message. * * @param[in] aMessage A reference to the message. * @param[out] aChallenge A reference to the Challenge data where to output the read value. * * @retval kErrorNone Successfully read the Challenge TLV. * @retval kErrorNotFound Challenge TLV was not found in the message. * @retval kErrorParse Challenge TLV was found but could not be parsed. * */ Error ReadChallenge(const Message &aMessage, Challenge &aChallenge); /** * This method appends a Response TLV to a message. * * @param[in] aMessage A reference to the message. * @param[in] aResponse A reference to the Response data. * * @retval kErrorNone Successfully appended the Response TLV. * @retval kErrorNoBufs Insufficient buffers available to append the Response TLV. * */ Error AppendResponse(Message &aMessage, const Challenge &aResponse); /** * This method reads Response TLV from a message. * * @param[in] aMessage A reference to the message. * @param[out] aResponse A reference to the Response data where to output the read value. * * @retval kErrorNone Successfully read the Response TLV. * @retval kErrorNotFound Response TLV was not found in the message. * @retval kErrorParse Response TLV was found but could not be parsed. * */ Error ReadResponse(const Message &aMessage, Challenge &aResponse); /** * This method appends a Link Frame Counter TLV to a message. * * @param[in] aMessage A reference to the message. * * @retval kErrorNone Successfully appended the Link Frame Counter TLV. * @retval kErrorNoBufs Insufficient buffers available to append the Link Frame Counter TLV. * */ Error AppendLinkFrameCounter(Message &aMessage); /** * This method reads Link and MLE Frame Counters from a message. * * Link Frame Counter TLV must be present in the message and its value is read into @p aLinkFrameCounter. If MLE * Frame Counter TLV is present in the message, its value is read into @p aMleFrameCounter. If the MLE Frame * Counter TLV is not present in the message, then @p aMleFrameCounter is set to same value as @p aLinkFrameCounter. * * @param[in] aMesssage A reference to the message to read from. * @param[out] aLinkFrameCounter A reference to an `uint32_t` to output the Link Frame Counter. * @param[out] aMleFrameCounter A reference to an `uint32_t` to output the MLE Frame Counter. * * @retval kErrorNone Successfully read the counters. * @retval kErrorNotFound Link Frame Counter TLV was not found in the message. * @retval kErrorParse TLVs are not well-formed. * */ Error ReadFrameCounters(const Message &aMessage, uint32_t &aLinkFrameCounter, uint32_t &aMleFrameCounter) const; /** * This method appends an MLE Frame Counter TLV to a message. * * @param[in] aMessage A reference to the message. * * @retval kErrorNone Successfully appended the Frame Counter TLV. * @retval kErrorNoBufs Insufficient buffers available to append the MLE Frame Counter TLV. * */ Error AppendMleFrameCounter(Message &aMessage); /** * This method appends an Address16 TLV to a message. * * @param[in] aMessage A reference to the message. * @param[in] aRloc16 The RLOC16 value. * * @retval kErrorNone Successfully appended the Address16 TLV. * @retval kErrorNoBufs Insufficient buffers available to append the Address16 TLV. * */ Error AppendAddress16(Message &aMessage, uint16_t aRloc16); /** * This method appends a Network Data TLV to the message. * * @param[in] aMessage A reference to the message. * @param[in] aStableOnly TRUE to append stable data, FALSE otherwise. * * @retval kErrorNone Successfully appended the Network Data TLV. * @retval kErrorNoBufs Insufficient buffers available to append the Network Data TLV. * */ Error AppendNetworkData(Message &aMessage, bool aStableOnly); /** * This method appends a TLV Request TLV to a message. * * @param[in] aMessage A reference to the message. * @param[in] aTlvs A pointer to the list of TLV types. * @param[in] aTlvsLength The number of TLV types in @p aTlvs * * @retval kErrorNone Successfully appended the TLV Request TLV. * @retval kErrorNoBufs Insufficient buffers available to append the TLV Request TLV. * */ Error AppendTlvRequest(Message &aMessage, const uint8_t *aTlvs, uint8_t aTlvsLength); /** * This method reads TLV Request TLV from a message. * * @param[in] aMessage A reference to the message. * @param[out] aRequestedTlvs A reference to output the read list of requested TLVs. * * @retval kErrorNone Successfully read the TLV. * @retval kErrorNotFound TLV was not found in the message. * @retval kErrorParse TLV was found but could not be parsed. * */ Error FindTlvRequest(const Message &aMessage, RequestedTlvs &aRequestedTlvs); /** * This method appends a Leader Data TLV to a message. * * @param[in] aMessage A reference to the message. * * @retval kErrorNone Successfully appended the Leader Data TLV. * @retval kErrorNoBufs Insufficient buffers available to append the Leader Data TLV. * */ Error AppendLeaderData(Message &aMessage); /** * This method reads Leader Data TLV from a message. * * @param[in] aMessage A reference to the message. * @param[out] aLeaderData A reference to output the Leader Data. * * @retval kErrorNone Successfully read the TLV. * @retval kErrorNotFound TLV was not found in the message. * @retval kErrorParse TLV was found but could not be parsed. * */ Error ReadLeaderData(const Message &aMessage, LeaderData &aLeaderData); /** * This method appends a Scan Mask TLV to a message. * * @param[in] aMessage A reference to the message. * @param[in] aScanMask The Scan Mask value. * * @retval kErrorNone Successfully appended the Scan Mask TLV. * @retval kErrorNoBufs Insufficient buffers available to append the Scan Mask TLV. * */ Error AppendScanMask(Message &aMessage, uint8_t aScanMask); /** * This method appends a Status TLV to a message. * * @param[in] aMessage A reference to the message. * @param[in] aStatus The Status value. * * @retval kErrorNone Successfully appended the Status TLV. * @retval kErrorNoBufs Insufficient buffers available to append the Status TLV. * */ Error AppendStatus(Message &aMessage, StatusTlv::Status aStatus); /** * This method appends a Link Margin TLV to a message. * * @param[in] aMessage A reference to the message. * @param[in] aLinkMargin The Link Margin value. * * @retval kErrorNone Successfully appended the Link Margin TLV. * @retval kErrorNoBufs Insufficient buffers available to append the Link Margin TLV. * */ Error AppendLinkMargin(Message &aMessage, uint8_t aLinkMargin); /** * This method appends a Version TLV to a message. * * @param[in] aMessage A reference to the message. * * @retval kErrorNone Successfully appended the Version TLV. * @retval kErrorNoBufs Insufficient buffers available to append the Version TLV. * */ Error AppendVersion(Message &aMessage); /** * This method appends an Address Registration TLV to a message. * * @param[in] aMessage A reference to the message. * @param[in] aMode Determines which addresses to include in the TLV (see `AddressRegistrationMode`). * * @retval kErrorNone Successfully appended the Address Registration TLV. * @retval kErrorNoBufs Insufficient buffers available to append the Address Registration TLV. * */ Error AppendAddressRegistration(Message &aMessage, AddressRegistrationMode aMode = kAppendAllAddresses); #if OPENTHREAD_CONFIG_TIME_SYNC_ENABLE /** * This method appends a Time Request TLV to a message. * * @param[in] aMessage A reference to the message. * * @retval kErrorNone Successfully appended the Time Request TLV. * @retval kErrorNoBufs Insufficient buffers available to append the Time Request TLV. * */ Error AppendTimeRequest(Message &aMessage); /** * This method appends a Time Parameter TLV to a message. * * @param[in] aMessage A reference to the message. * * @retval kErrorNone Successfully appended the Time Parameter TLV. * @retval kErrorNoBufs Insufficient buffers available to append the Time Parameter TLV. * */ Error AppendTimeParameter(Message &aMessage); /** * This method appends a XTAL Accuracy TLV to a message. * * @param[in] aMessage A reference to the message. * * @retval kErrorNone Successfully appended the XTAL Accuracy TLV. * @retval kErrorNoBufs Insufficient buffers available to append the XTAl Accuracy TLV. * */ Error AppendXtalAccuracy(Message &aMessage); #endif // OPENTHREAD_CONFIG_TIME_SYNC_ENABLE #if (OPENTHREAD_FTD && OPENTHREAD_CONFIG_MAC_CSL_TRANSMITTER_ENABLE) || OPENTHREAD_CONFIG_MAC_CSL_RECEIVER_ENABLE /** * This method appends a CSL Channel TLV to a message. * * @param[in] aMessage A reference to the message. * * @retval kErrorNone Successfully appended the CSL Channel TLV. * @retval kErrorNoBufs Insufficient buffers available to append the CSL Channel TLV. * */ Error AppendCslChannel(Message &aMessage); /** * This method appends a CSL Sync Timeout TLV to a message. * * @param[in] aMessage A reference to the message. * * @retval kErrorNone Successfully appended the CSL Timeout TLV. * @retval kErrorNoBufs Insufficient buffers available to append the CSL Timeout TLV. * */ Error AppendCslTimeout(Message &aMessage); #endif // (OPENTHREAD_FTD && OPENTHREAD_CONFIG_MAC_CSL_TRANSMITTER_ENABLE) || OPENTHREAD_CONFIG_MAC_CSL_RECEIVER_ENABLE /** * This method appends a Active Timestamp TLV to a message. * * @param[in] aMessage A reference to the message. * * @retval kErrorNone Successfully appended the Active Timestamp TLV. * @retval kErrorNoBufs Insufficient buffers available to append the Active Timestamp TLV. * */ Error AppendActiveTimestamp(Message &aMessage); /** * This method appends a Pending Timestamp TLV to a message. * * @param[in] aMessage A reference to the message. * * @retval kErrorNone Successfully appended the Pending Timestamp TLV. * @retval kErrorNoBufs Insufficient buffers available to append the Pending Timestamp TLV. * */ Error AppendPendingTimestamp(Message &aMessage); /** * This method checks if the destination is reachable. * * @param[in] aMeshDest The RLOC16 of the destination. * @param[in] aIp6Header The IPv6 header of the message. * * @retval kErrorNone The destination is reachable. * @retval kErrorNoRoute The destination is not reachable and the message should be dropped. * */ Error CheckReachability(uint16_t aMeshDest, Ip6::Header &aIp6Header); /** * This method returns the next hop towards an RLOC16 destination. * * @param[in] aDestination The RLOC16 of the destination. * * @returns A RLOC16 of the next hop if a route is known, kInvalidRloc16 otherwise. * */ Mac::ShortAddress GetNextHop(uint16_t aDestination) const; /** * This method generates an MLE Data Request message. * * @param[in] aDestination A reference to the IPv6 address of the destination. * @param[in] aTlvs A pointer to requested TLV types. * @param[in] aTlvsLength The number of TLV types in @p aTlvs. * @param[in] aDelay Delay in milliseconds before the Data Request message is sent. * @param[in] aExtraTlvs A pointer to extra TLVs. * @param[in] aExtraTlvsLength Length of extra TLVs. * * @retval kErrorNone Successfully generated an MLE Data Request message. * @retval kErrorNoBufs Insufficient buffers to generate the MLE Data Request message. * */ Error SendDataRequest(const Ip6::Address &aDestination, const uint8_t * aTlvs, uint8_t aTlvsLength, uint16_t aDelay, const uint8_t * aExtraTlvs = nullptr, uint8_t aExtraTlvsLength = 0); /** * This method generates an MLE Child Update Request message. * * @retval kErrorNone Successfully generated an MLE Child Update Request message. * @retval kErrorNoBufs Insufficient buffers to generate the MLE Child Update Request message. * */ Error SendChildUpdateRequest(void); /** * This method generates an MLE Child Update Response message. * * @param[in] aTlvs A pointer to requested TLV types. * @param[in] aNumTlvs The number of TLV types in @p aTlvs. * @param[in] aChallenge The Challenge for the response. * * @retval kErrorNone Successfully generated an MLE Child Update Response message. * @retval kErrorNoBufs Insufficient buffers to generate the MLE Child Update Response message. * */ Error SendChildUpdateResponse(const uint8_t *aTlvs, uint8_t aNumTlvs, const Challenge &aChallenge); /** * This method submits an MLE message to the UDP socket. * * @param[in] aMessage A reference to the message. * @param[in] aDestination A reference to the IPv6 address of the destination. * * @retval kErrorNone Successfully submitted the MLE message. * @retval kErrorNoBufs Insufficient buffers to form the rest of the MLE message. * */ Error SendMessage(Message &aMessage, const Ip6::Address &aDestination); /** * This method sets the RLOC16 assigned to the Thread interface. * * @param[in] aRloc16 The RLOC16 to set. * */ void SetRloc16(uint16_t aRloc16); /** * This method sets the Device State to Detached. * */ void SetStateDetached(void); /** * This method sets the Device State to Child. * */ void SetStateChild(uint16_t aRloc16); /** * This method sets the Leader's Partition ID, Weighting, and Router ID values. * * @param[in] aPartitionId The Leader's Partition ID value. * @param[in] aWeighting The Leader's Weighting value. * @param[in] aLeaderRouterId The Leader's Router ID value. * */ void SetLeaderData(uint32_t aPartitionId, uint8_t aWeighting, uint8_t aLeaderRouterId); /** * This method adds a message to the message queue. The queued message will be transmitted after given delay. * * @param[in] aMessage The message to transmit after given delay. * @param[in] aDestination The IPv6 address of the recipient of the message. * @param[in] aDelay The delay in milliseconds before transmission of the message. * * @retval kErrorNone Successfully queued the message to transmit after the delay. * @retval kErrorNoBufs Insufficient buffers to queue the message. * */ Error AddDelayedResponse(Message &aMessage, const Ip6::Address &aDestination, uint16_t aDelay); #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MLE == 1) /** * This static method emits a log message with an IPv6 address. * * @param[in] aAction The message action (send/receive/delay, etc). * @param[in] aType The message type. * @param[in] aAddress The IPv6 address of the peer. * */ static void Log(MessageAction aAction, MessageType aType, const Ip6::Address &aAddress); /** * This static method emits a log message with an IPv6 address and RLOC16. * * @param[in] aAction The message action (send/receive/delay, etc). * @param[in] aType The message type. * @param[in] aAddress The IPv6 address of the peer. * @param[in] aRloc The RLOC16. * */ static void Log(MessageAction aAction, MessageType aType, const Ip6::Address &aAddress, uint16_t aRloc); #else static void Log(MessageAction, MessageType, const Ip6::Address &) {} static void Log(MessageAction, MessageType, const Ip6::Address &, uint16_t) {} #endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MLE == 1) #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN) && (OPENTHREAD_CONFIG_LOG_MLE == 1) /** * This static method emits a log message indicating an error in processing of a message. * * Note that log message is emitted only if there is an error, i.e., @p aError is not `kErrorNone`. The log * message will have the format ""Failed to process {aMessageString} : {ErrorString}"". * * @param[in] aType The message type. * @param[in] aError The error in processing of the message. * */ static void LogProcessError(MessageType aType, Error aError); /** * This static method emits a log message indicating an error when sending a message. * * Note that log message is emitted only if there is an error, i.e. @p aError is not `kErrorNone`. The log * message will have the format ""Failed to send {Message Type} : {ErrorString}"". * * @param[in] aType The message type. * @param[in] aError The error in sending the message. * */ static void LogSendError(MessageType aType, Error aError); #else static void LogProcessError(MessageType, Error) {} static void LogSendError(MessageType, Error) {} #endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN) && (OPENTHREAD_CONFIG_LOG_MLE == 1) /** * This method triggers MLE Announce on previous channel after the Thread device successfully * attaches and receives the new Active Commissioning Dataset if needed. * * MTD would send Announce immediately after attached. * FTD would delay to send Announce after tried to become Router or decided to stay in REED role. * */ void InformPreviousChannel(void); /** * This method indicates whether or not in announce attach process. * * @retval true if attaching/attached on the announced parameters, false otherwise. * */ bool IsAnnounceAttach(void) const { return mAlternatePanId != Mac::kPanIdBroadcast; } #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && (OPENTHREAD_CONFIG_LOG_MLE == 1) /** * This method converts an `AttachMode` enumeration value into a human-readable string. * * @param[in] aMode An attach mode * * @returns A human-readable string corresponding to the attach mode. * */ static const char *AttachModeToString(AttachMode aMode); /** * This method converts an `AttachState` enumeration value into a human-readable string. * * @param[in] aState An attach state * * @returns A human-readable string corresponding to the attach state. * */ static const char *AttachStateToString(AttachState aState); /** * This method converts a `ReattachState` enumeration value into a human-readable string. * * @param[in] aState A reattach state * * @returns A human-readable string corresponding to the reattach state. * */ static const char *ReattachStateToString(ReattachState aState); #endif #if OPENTHREAD_CONFIG_MLE_LINK_METRICS_ENABLE /** * This method sends a Link Metrics Management Request message. * * @param[in] aDestination A reference to the IPv6 address of the destination. * @param[in] aSubTlvs A pointer to the buffer of the sub-TLVs in the message. * @param[in] aLength The overall length of @p aSubTlvs. * * @retval kErrorNone Successfully sent a Link Metrics Management Request. * @retval kErrorNoBufs Insufficient buffers to generate the MLE Link Metrics Management Request message. * */ Error SendLinkMetricsManagementRequest(const Ip6::Address &aDestination, const uint8_t *aSubTlvs, uint8_t aLength); /** * This method sends an MLE Link Probe message. * * @param[in] aDestination A reference to the IPv6 address of the destination. * @param[in] aSeriesId The Series ID [1, 254] which the Probe message targets at. * @param[in] aBuf A pointer to the data payload. * @param[in] aLength The length of the data payload in Link Probe TLV, [0, 64]. * * @retval kErrorNone Successfully sent a Link Metrics Management Request. * @retval kErrorNoBufs Insufficient buffers to generate the MLE Link Metrics Management Request message. * @retval kErrorInvalidArgs Series ID is not a valid value, not within range [1, 254]. * */ Error SendLinkProbe(const Ip6::Address &aDestination, uint8_t aSeriesId, uint8_t *aBuf, uint8_t aLength); #endif Ip6::NetifUnicastAddress mLeaderAloc; ///< Leader anycast locator LeaderData mLeaderData; ///< Last received Leader Data TLV. bool mRetrieveNewNetworkData; ///< Indicating new Network Data is needed if set. DeviceRole mRole; ///< Current Thread role. Router mParent; ///< Parent information. Router mParentCandidate; ///< Parent candidate information. NeighborTable mNeighborTable; ///< The neighbor table. DeviceMode mDeviceMode; ///< Device mode setting. AttachState mAttachState; ///< The parent request state. ReattachState mReattachState; ///< Reattach state uint16_t mAttachCounter; ///< Attach attempt counter. uint16_t mAnnounceDelay; ///< Delay in between sending Announce messages during attach. TimerMilli mAttachTimer; ///< The timer for driving the attach process. TimerMilli mDelayedResponseTimer; ///< The timer to delay MLE responses. TimerMilli mMessageTransmissionTimer; ///< The timer for (re-)sending of MLE messages (e.g. Child Update). uint8_t mParentLeaderCost; private: enum { kMleHopLimit = 255, kMleSecurityTagSize = 4, // Security tag size in bytes. // Parameters related to ""periodic parent search"" feature (CONFIG_ENABLE_PERIODIC_PARENT_SEARCH). // All timer intervals are converted to milliseconds. kParentSearchCheckInterval = (OPENTHREAD_CONFIG_PARENT_SEARCH_CHECK_INTERVAL * 1000u), kParentSearchBackoffInterval = (OPENTHREAD_CONFIG_PARENT_SEARCH_BACKOFF_INTERVAL * 1000u), kParentSearchJitterInterval = (15 * 1000u), kParentSearchRssThreadhold = OPENTHREAD_CONFIG_PARENT_SEARCH_RSS_THRESHOLD, }; // Parameters for ""attach backoff"" feature (CONFIG_ENABLE_ATTACH_BACKOFF) - Intervals are in milliseconds. enum : uint32_t { kAttachBackoffMinInterval = OPENTHREAD_CONFIG_MLE_ATTACH_BACKOFF_MINIMUM_INTERVAL, kAttachBackoffMaxInterval = OPENTHREAD_CONFIG_MLE_ATTACH_BACKOFF_MAXIMUM_INTERVAL, kAttachBackoffJitter = OPENTHREAD_CONFIG_MLE_ATTACH_BACKOFF_JITTER_INTERVAL, kAttachBackoffDelayToResetCounter = OPENTHREAD_CONFIG_MLE_ATTACH_BACKOFF_DELAY_TO_RESET_BACKOFF_INTERVAL, }; enum ParentRequestType { kParentRequestTypeRouters, ///< Parent Request to all routers. kParentRequestTypeRoutersAndReeds, ///< Parent Request to all routers and REEDs. }; enum ChildUpdateRequestState { kChildUpdateRequestNone, ///< No pending or active Child Update Request. kChildUpdateRequestPending, ///< Pending Child Update Request due to relative OT_CHANGED event. kChildUpdateRequestActive, ///< Child Update Request has been sent and Child Update Response is expected. }; enum DataRequestState { kDataRequestNone, ///< Not waiting for a Data Response. kDataRequestActive, ///< Data Request has been sent, Data Response is expected. }; struct DelayedResponseMetadata { Error AppendTo(Message &aMessage) const { return aMessage.Append(*this); } void ReadFrom(const Message &aMessage); void RemoveFrom(Message &aMessage) const; Ip6::Address mDestination; // IPv6 address of the message destination. TimeMilli mSendTime; // Time when the message shall be sent. }; OT_TOOL_PACKED_BEGIN class Header { public: enum SecuritySuite { k154Security = 0, kNoSecurity = 255, }; void Init(void) { mSecuritySuite = k154Security; mSecurityControl = Mac::Frame::kSecEncMic32; } bool IsValid(void) const { return (mSecuritySuite == kNoSecurity) || (mSecuritySuite == k154Security && mSecurityControl == (Mac::Frame::kKeyIdMode2 | Mac::Frame::kSecEncMic32)); } uint8_t GetLength(void) const { return sizeof(mSecuritySuite) + sizeof(mCommand) + ((mSecuritySuite == k154Security) ? sizeof(mSecurityControl) + sizeof(mFrameCounter) + sizeof(mKeySource) + sizeof(mKeyIndex) : 0); } SecuritySuite GetSecuritySuite(void) const { return static_cast(mSecuritySuite); } void SetSecuritySuite(SecuritySuite aSecuritySuite) { mSecuritySuite = static_cast(aSecuritySuite); } uint8_t GetHeaderLength(void) const { return sizeof(mSecurityControl) + sizeof(mFrameCounter) + sizeof(mKeySource) + sizeof(mKeyIndex); } const uint8_t *GetBytes(void) const { return reinterpret_cast(&mSecuritySuite); } uint8_t GetSecurityControl(void) const { return mSecurityControl; } bool IsKeyIdMode2(void) const { return (mSecurityControl & Mac::Frame::kKeyIdModeMask) == Mac::Frame::kKeyIdMode2; } void SetKeyIdMode2(void) { mSecurityControl = (mSecurityControl & ~Mac::Frame::kKeyIdModeMask) | Mac::Frame::kKeyIdMode2; } uint32_t GetKeyId(void) const { return Encoding::BigEndian::HostSwap32(mKeySource); } void SetKeyId(uint32_t aKeySequence) { mKeySource = Encoding::BigEndian::HostSwap32(aKeySequence); mKeyIndex = (aKeySequence & 0x7f) + 1; } uint32_t GetFrameCounter(void) const { return Encoding::LittleEndian::HostSwap32(mFrameCounter); } void SetFrameCounter(uint32_t aFrameCounter) { mFrameCounter = Encoding::LittleEndian::HostSwap32(aFrameCounter); } Command GetCommand(void) const { return static_cast((mSecuritySuite == kNoSecurity) ? mSecurityControl : mCommand); } void SetCommand(Command aCommand) { if (mSecuritySuite == kNoSecurity) { mSecurityControl = static_cast(aCommand); } else { mCommand = static_cast(aCommand); } } private: uint8_t mSecuritySuite; uint8_t mSecurityControl; uint32_t mFrameCounter; uint32_t mKeySource; uint8_t mKeyIndex; uint8_t mCommand; } OT_TOOL_PACKED_END; void HandleNotifierEvents(Events aEvents); static void HandleAttachTimer(Timer &aTimer); void HandleAttachTimer(void); static void HandleDelayedResponseTimer(Timer &aTimer); void HandleDelayedResponseTimer(void); static void HandleMessageTransmissionTimer(Timer &aTimer); void HandleMessageTransmissionTimer(void); static void HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo); void HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); void ScheduleMessageTransmissionTimer(void); Error ReadChallengeOrResponse(const Message &aMessage, uint8_t aTlvType, Challenge &aBuffer); void HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, Neighbor *aNeighbor); void HandleChildIdResponse(const Message & aMessage, const Ip6::MessageInfo &aMessageInfo, const Neighbor * aNeighbor); void HandleChildUpdateRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, Neighbor *aNeighbor); void HandleChildUpdateResponse(const Message & aMessage, const Ip6::MessageInfo &aMessageInfo, const Neighbor * aNeighbor); void HandleDataResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, const Neighbor *aNeighbor); void HandleParentResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, uint32_t aKeySequence); void HandleAnnounce(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo); #if OPENTHREAD_CONFIG_MLE_LINK_METRICS_ENABLE void HandleLinkMetricsManagementRequest(const Message & aMessage, const Ip6::MessageInfo &aMessageInfo, Neighbor * aNeighbor); void HandleLinkMetricsManagementResponse(const Message & aMessage, const Ip6::MessageInfo &aMessageInfo, Neighbor * aNeighbor); void HandleLinkProbe(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, Neighbor *aNeighbor); #endif Error HandleLeaderData(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo); void ProcessAnnounce(void); bool HasUnregisteredAddress(void); uint32_t GetAttachStartDelay(void) const; Error SendParentRequest(ParentRequestType aType); Error SendChildIdRequest(void); Error SendOrphanAnnounce(void); bool PrepareAnnounceState(void); void SendAnnounce(uint8_t aChannel, bool aOrphanAnnounce, const Ip6::Address &aDestination); #if OPENTHREAD_CONFIG_MLE_LINK_METRICS_ENABLE Error SendLinkMetricsManagementResponse(const Ip6::Address &aDestination, LinkMetrics::LinkMetricsStatus aStatus); #endif uint32_t Reattach(void); bool IsBetterParent(uint16_t aRloc16, uint8_t aLinkQuality, uint8_t aLinkMargin, const ConnectivityTlv &aConnectivityTlv, uint8_t aVersion); bool IsNetworkDataNewer(const LeaderData &aLeaderData); #if OPENTHREAD_CONFIG_TMF_NETDATA_SERVICE_ENABLE /** * This method scans for network data from the leader and updates IP addresses assigned to this * interface to make sure that all Service ALOCs (0xfc10-0xfc1f) are properly set. */ void UpdateServiceAlocs(void); #endif #if OPENTHREAD_CONFIG_MLE_INFORM_PREVIOUS_PARENT_ON_REATTACH void InformPreviousParent(void); #endif #if OPENTHREAD_CONFIG_PARENT_SEARCH_ENABLE static void HandleParentSearchTimer(Timer &aTimer); void HandleParentSearchTimer(void); void StartParentSearchTimer(void); void UpdateParentSearchState(void); #endif #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_WARN) && (OPENTHREAD_CONFIG_LOG_MLE == 1) static void LogError(MessageAction aAction, MessageType aType, Error aError); static const char *MessageActionToString(MessageAction aAction); static const char *MessageTypeToString(MessageType aType); static const char *MessageTypeActionToSuffixString(MessageType aType, MessageAction aAction); #endif MessageQueue mDelayedResponses; Challenge mParentRequestChallenge; AttachMode mParentRequestMode; int8_t mParentPriority; uint8_t mParentLinkQuality3; uint8_t mParentLinkQuality2; uint8_t mParentLinkQuality1; uint16_t mParentSedBufferSize; uint8_t mParentSedDatagramCount; uint8_t mChildUpdateAttempts; ChildUpdateRequestState mChildUpdateRequestState; uint8_t mDataRequestAttempts; DataRequestState mDataRequestState; AddressRegistrationMode mAddressRegistrationMode; bool mHasRestored; uint8_t mParentLinkMargin; bool mParentIsSingleton; bool mReceivedResponseFromParent; LeaderData mParentLeaderData; Challenge mParentCandidateChallenge; Ip6::Udp::Socket mSocket; uint32_t mTimeout; #if OPENTHREAD_CONFIG_MLE_INFORM_PREVIOUS_PARENT_ON_REATTACH uint16_t mPreviousParentRloc; #endif #if OPENTHREAD_CONFIG_PARENT_SEARCH_ENABLE bool mParentSearchIsInBackoff : 1; bool mParentSearchBackoffWasCanceled : 1; bool mParentSearchRecentlyDetached : 1; TimeMilli mParentSearchBackoffCancelTime; TimerMilli mParentSearchTimer; #endif uint8_t mAnnounceChannel; uint8_t mAlternateChannel; uint16_t mAlternatePanId; uint64_t mAlternateTimestamp; #if OPENTHREAD_CONFIG_TMF_NETDATA_SERVICE_ENABLE Ip6::NetifUnicastAddress mServiceAlocs[kMaxServiceAlocs]; #endif otMleCounters mCounters; Ip6::NetifUnicastAddress mLinkLocal64; Ip6::NetifUnicastAddress mMeshLocal64; Ip6::NetifUnicastAddress mMeshLocal16; Ip6::NetifMulticastAddress mLinkLocalAllThreadNodes; Ip6::NetifMulticastAddress mRealmLocalAllThreadNodes; otThreadParentResponseCallback mParentResponseCb; void * mParentResponseCbContext; }; } // namespace Mle /** * @} * */ } // namespace ot #endif // MLE_HPP_ ",16241,True,3221.8829902324205,median "/*************************************************************************/ /* csharp_script.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* ""Software""), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include ""csharp_script.h"" #include #include ""os/file_access.h"" #include ""os/os.h"" #include ""os/thread.h"" #include ""project_settings.h"" #ifdef TOOLS_ENABLED #include ""editor/bindings_generator.h"" #include ""editor/csharp_project.h"" #include ""editor/editor_node.h"" #include ""editor/godotsharp_editor.h"" #include ""utils/string_utils.h"" #endif #include ""godotsharp_dirs.h"" #include ""mono_gd/gd_mono_class.h"" #include ""mono_gd/gd_mono_marshal.h"" #include ""signal_awaiter_utils.h"" #include ""utils/macros.h"" #include ""utils/thread_local.h"" #define CACHED_STRING_NAME(m_var) (CSharpLanguage::get_singleton()->get_string_names().m_var) #ifdef TOOLS_ENABLED static bool _create_project_solution_if_needed() { String sln_path = GodotSharpDirs::get_project_sln_path(); String csproj_path = GodotSharpDirs::get_project_csproj_path(); if (!FileAccess::exists(sln_path) || !FileAccess::exists(csproj_path)) { // A solution does not yet exist, create a new one CRASH_COND(GodotSharpEditor::get_singleton() == NULL); return GodotSharpEditor::get_singleton()->call(""_create_project_solution""); } return true; } #endif CSharpLanguage *CSharpLanguage::singleton = NULL; String CSharpLanguage::get_name() const { return ""C#""; } String CSharpLanguage::get_type() const { return ""CSharpScript""; } String CSharpLanguage::get_extension() const { return ""cs""; } Error CSharpLanguage::execute_file(const String &p_path) { // ?? return OK; } #ifdef TOOLS_ENABLED void gdsharp_editor_init_callback() { EditorNode *editor = EditorNode::get_singleton(); editor->add_child(memnew(GodotSharpEditor(editor))); } #endif void CSharpLanguage::init() { gdmono = memnew(GDMono); gdmono->initialize(); #ifdef MONO_GLUE_DISABLED WARN_PRINT(""This binary is built with `mono_glue=no` and cannot be used for scripting""); #endif #if defined(TOOLS_ENABLED) && defined(DEBUG_METHODS_ENABLED) if (gdmono->get_editor_tools_assembly() != NULL) { List cmdline_args = OS::get_singleton()->get_cmdline_args(); BindingsGenerator::handle_cmdline_args(cmdline_args); } #endif #ifdef TOOLS_ENABLED EditorNode::add_init_callback(&gdsharp_editor_init_callback); GLOBAL_DEF(""mono/export/include_scripts_content"", true); #endif } void CSharpLanguage::finish() { finalizing = true; #ifdef TOOLS_ENABLED // Must be here, to avoid StringName leaks if (BindingsGenerator::singleton) { memdelete(BindingsGenerator::singleton); BindingsGenerator::singleton = NULL; } #endif // Release gchandle bindings before finalizing mono runtime gchandle_bindings.clear(); if (gdmono) { memdelete(gdmono); gdmono = NULL; } finalizing = false; } void CSharpLanguage::get_reserved_words(List *p_words) const { static const char *_reserved_words[] = { // Reserved keywords ""abstract"", ""as"", ""base"", ""bool"", ""break"", ""byte"", ""case"", ""catch"", ""char"", ""checked"", ""class"", ""const"", ""continue"", ""decimal"", ""default"", ""delegate"", ""do"", ""double"", ""else"", ""enum"", ""event"", ""explicit"", ""extern"", ""false"", ""finally"", ""fixed"", ""float"", ""for"", ""foreach"", ""goto"", ""if"", ""implicit"", ""in"", ""int"", ""interface"", ""internal"", ""is"", ""lock"", ""long"", ""namespace"", ""new"", ""null"", ""object"", ""operator"", ""out"", ""override"", ""params"", ""private"", ""protected"", ""public"", ""readonly"", ""ref"", ""return"", ""sbyte"", ""sealed"", ""short"", ""sizeof"", ""stackalloc"", ""static"", ""string"", ""struct"", ""switch"", ""this"", ""throw"", ""true"", ""try"", ""typeof"", ""uint"", ""ulong"", ""unchecked"", ""unsafe"", ""ushort"", ""using"", ""virtual"", ""void"", ""volatile"", ""while"", // Contextual keywords. Not reserved words, but I guess we should include // them because this seems to be used only for syntax highlighting. ""add"", ""alias"", ""ascending"", ""async"", ""await"", ""by"", ""descending"", ""dynamic"", ""equals"", ""from"", ""get"", ""global"", ""group"", ""into"", ""join"", ""let"", ""nameof"", ""on"", ""orderby"", ""partial"", ""remove"", ""select"", ""set"", ""value"", ""var"", ""when"", ""where"", ""yield"", 0 }; const char **w = _reserved_words; while (*w) { p_words->push_back(*w); w++; } } void CSharpLanguage::get_comment_delimiters(List *p_delimiters) const { p_delimiters->push_back(""//""); // single-line comment p_delimiters->push_back(""/* */""); // delimited comment } void CSharpLanguage::get_string_delimiters(List *p_delimiters) const { p_delimiters->push_back(""' '""); // character literal p_delimiters->push_back(""\\"" \\""""); // regular string literal p_delimiters->push_back(""@\\"" \\""""); // verbatim string literal } static String get_base_class_name(const String &p_base_class_name, const String p_class_name) { String base_class = p_base_class_name; if (p_class_name == base_class) { base_class = ""Godot."" + base_class; } return base_class; } Ref