text stringlengths 1 1.05M |
|---|
Total: 6.66s
ROUTINE ======================== main.(*Graph).buildAdjList
830ms 2.60s (flat, cum) 39.04% of Total
. . 10ca200: MOVQ GS:0x30, CX ;graph.go:101
. . 10ca209: LEAQ -0x60(SP), AX
. . 10ca20e: CMPQ 0x10(CX), AX
. . 10ca212: JBE 0x10ca6be
. . 10ca218: SUBQ $0xe0, SP
. . 10ca21f: MOVQ BP, 0xd8(SP)
. . 10ca227: LEAQ 0xd8(SP), BP
. . 10ca22f: XORL AX, AX
. . 10ca231: XORL CX, CX
. . 10ca233: JMP 0x10ca4df ;graph.go:103
. . 10ca238: MOVQ 0x88(SP), R10 ;graph.go:109
. . 10ca240: LEAQ 0x1(R10), R9
. . 10ca244: MOVQ 0x78(SP), R10
. . 10ca249: MOVQ 0x70(SP), R11
. . 10ca24e: MOVQ 0x98(SP), R12
. . 10ca256: MOVQ 0x68(SP), R13
. . 10ca25b: MOVQ 0xc0(SP), R14
. . 10ca263: MOVQ R10, AX
. . 10ca266: MOVQ 0x50(SP), CX ;graph.go:106
. . 10ca26b: MOVQ R11, DX ;graph.go:110
. . 10ca26e: MOVQ 0xe8(SP), BX
. . 10ca276: MOVQ R12, SI
. . 10ca279: MOVQ R13, DI
. . 10ca27c: MOVQ R14, R8 ;graph.go:109
. . 10ca27f: CMPQ AX, R9
. . 10ca282: JGE 0x10ca4d6
670ms 670ms 10ca288: MOVQ 0(R8)(R9*8), R10 ;main.(*Graph).buildAdjList graph.go:109
. . 10ca28c: MOVQ 0x8(BX), R11 ;graph.go:110
. . 10ca290: MOVQ 0(BX), R12
. . 10ca293: CMPQ R11, R10
. . 10ca296: JAE 0x10ca6b2
. . 10ca29c: MOVQ R9, 0x88(SP) ;graph.go:109
. . 10ca2a4: MOVQ R10, 0x58(SP)
. . 10ca2a9: LEAQ 0(R10)(R10*2), AX ;graph.go:110
. . 10ca2ad: MOVQ AX, 0x80(SP)
. . 10ca2b5: MOVQ 0(R12)(AX*8), CX
60ms 60ms 10ca2b9: MOVQ 0x10(R12)(AX*8), BX ;main.(*Graph).buildAdjList graph.go:110
10ms 10ms 10ca2be: MOVQ 0x8(R12)(AX*8), R8
. . 10ca2c3: MOVQ SI, 0(SP) ;graph.go:110
. . 10ca2c7: MOVQ DI, 0x8(SP)
. . 10ca2cc: MOVQ DX, 0x10(SP)
. . 10ca2d1: MOVQ CX, 0x18(SP)
. . 10ca2d6: MOVQ R8, 0x20(SP)
. . 10ca2db: MOVQ BX, 0x28(SP)
. 120ms 10ca2e0: CALL main.distance(SB) ;main.(*Graph).buildAdjList graph.go:110
. . 10ca2e5: CMPQ $0x1, 0x30(SP) ;graph.go:110
20ms 20ms 10ca2eb: JNE 0x10ca4bc ;main.(*Graph).buildAdjList graph.go:110
. . 10ca2f1: MOVQ 0xe8(SP), DX ;graph.go:111
. . 10ca2f9: MOVQ 0x18(DX), BX
. . 10ca2fd: MOVQ 0x20(DX), CX
. . 10ca301: MOVQ 0x60(SP), AX
. . 10ca306: CMPQ CX, AX
. . 10ca309: JAE 0x10ca6ad
. . 10ca30f: MOVQ 0x90(SP), SI
. . 10ca317: MOVQ 0x10(BX)(SI*8), DI
. . 10ca31c: MOVQ 0x8(BX)(SI*8), R8
. . 10ca321: MOVQ 0(BX)(SI*8), R9
. . 10ca325: LEAQ 0x1(R8), R10
. . 10ca329: LEAQ 0(BX)(SI*8), R11
. . 10ca32d: CMPQ DI, R10
. . 10ca330: JA 0x10ca425
. . 10ca336: LEAQ 0x1(R8), DI
. . 10ca33a: MOVQ DI, 0x8(BX)(SI*8)
. . 10ca33f: MOVQ 0x58(SP), BX
. . 10ca344: MOVQ BX, 0(R9)(R8*8)
. . 10ca348: MOVQ 0x20(DX), CX ;graph.go:112
. . 10ca34c: MOVQ 0x18(DX), DI
. . 10ca350: CMPQ CX, BX
. . 10ca353: JAE 0x10ca6a5
. . 10ca359: MOVQ 0x80(SP), BX
. . 10ca361: MOVQ 0(DI)(BX*8), R8
50ms 50ms 10ca365: MOVQ 0x10(DI)(BX*8), R9 ;main.(*Graph).buildAdjList graph.go:112
. . 10ca36a: MOVQ 0x8(DI)(BX*8), R10 ;graph.go:112
. . 10ca36f: LEAQ 0x1(R10), R11
. . 10ca373: LEAQ 0(DI)(BX*8), R12
. . 10ca377: CMPQ R9, R11
. . 10ca37a: JA 0x10ca38e
. . 10ca37c: LEAQ 0x1(R10), R9
. . 10ca380: MOVQ R9, 0x8(DI)(BX*8)
. . 10ca385: MOVQ AX, 0(R8)(R10*8)
. . 10ca389: JMP 0x10ca238
. . 10ca38e: MOVQ R12, 0xb8(SP)
. . 10ca396: MOVQ DI, 0xb0(SP)
. . 10ca39e: LEAQ runtime.types+85760(SB), AX
. . 10ca3a5: MOVQ AX, 0(SP)
. . 10ca3a9: MOVQ R8, 0x8(SP)
. . 10ca3ae: MOVQ R10, 0x10(SP)
. . 10ca3b3: MOVQ R9, 0x18(SP)
. . 10ca3b8: MOVQ R11, 0x20(SP)
. 230ms 10ca3bd: CALL runtime.growslice(SB) ;main.(*Graph).buildAdjList graph.go:112
. . 10ca3c2: MOVQ 0x28(SP), AX ;graph.go:112
. . 10ca3c7: MOVQ 0x30(SP), CX
. . 10ca3cc: MOVQ 0x38(SP), DX
. . 10ca3d1: MOVQ 0x80(SP), BX
. . 10ca3d9: MOVQ 0xb0(SP), SI
. . 10ca3e1: MOVQ DX, 0x10(SI)(BX*8)
. . 10ca3e6: CMPL $0x0, runtime.writeBarrier(SB)
. . 10ca3ed: JNE 0x10ca416
. . 10ca3ef: MOVQ AX, 0(SI)(BX*8)
. . 10ca3f3: MOVQ 0xe8(SP), DX ;graph.go:110
. . 10ca3fb: MOVQ SI, DI ;graph.go:112
. . 10ca3fe: MOVQ CX, R10
. . 10ca401: MOVQ AX, R8
. . 10ca404: MOVQ 0x60(SP), AX
. . 10ca409: MOVQ 0x90(SP), SI ;graph.go:111
. . 10ca411: JMP 0x10ca37c ;graph.go:112
. . 10ca416: MOVQ 0xb8(SP), DI
. . 10ca41e: CALL runtime.gcWriteBarrier(SB)
. . 10ca423: JMP 0x10ca3f3
. . 10ca425: MOVQ BX, 0xa8(SP) ;graph.go:111
. . 10ca42d: MOVQ R11, 0xa0(SP)
. . 10ca435: LEAQ runtime.types+85760(SB), AX
. . 10ca43c: MOVQ AX, 0(SP)
. . 10ca440: MOVQ R9, 0x8(SP)
. . 10ca445: MOVQ R8, 0x10(SP)
. . 10ca44a: MOVQ DI, 0x18(SP)
. . 10ca44f: MOVQ R10, 0x20(SP)
. 210ms 10ca454: CALL runtime.growslice(SB) ;main.(*Graph).buildAdjList graph.go:111
. . 10ca459: MOVQ 0x28(SP), AX ;graph.go:111
. . 10ca45e: MOVQ 0x30(SP), CX
. . 10ca463: MOVQ 0x38(SP), DX
. . 10ca468: MOVQ 0x90(SP), BX
. . 10ca470: MOVQ 0xa8(SP), SI
. . 10ca478: MOVQ DX, 0x10(SI)(BX*8)
. . 10ca47d: CMPL $0x0, runtime.writeBarrier(SB)
. . 10ca484: JNE 0x10ca4ad
. . 10ca486: MOVQ AX, 0(SI)(BX*8)
. . 10ca48a: MOVQ 0xe8(SP), DX ;graph.go:112
. . 10ca492: MOVQ SI, BX ;graph.go:111
. . 10ca495: MOVQ 0x90(SP), SI
. . 10ca49d: MOVQ CX, R8
. . 10ca4a0: MOVQ AX, R9
. . 10ca4a3: MOVQ 0x60(SP), AX ;graph.go:112
. . 10ca4a8: JMP 0x10ca336 ;graph.go:111
. . 10ca4ad: MOVQ 0xa0(SP), DI
. . 10ca4b5: CALL runtime.gcWriteBarrier(SB)
. . 10ca4ba: JMP 0x10ca48a
. . 10ca4bc: MOVQ 0x60(SP), AX ;graph.go:103
. . 10ca4c1: MOVQ 0xe8(SP), DX ;graph.go:110
. . 10ca4c9: MOVQ 0x90(SP), SI ;graph.go:111
. . 10ca4d1: JMP 0x10ca238 ;graph.go:109
. . 10ca4d6: MOVQ 0x60(SP), DX ;graph.go:103
. . 10ca4db: LEAQ 0x1(DX), AX
. . 10ca4df: MOVQ 0xe8(SP), DX
. . 10ca4e7: MOVQ 0x8(DX), BX
. . 10ca4eb: MOVQ 0(DX), SI
. . 10ca4ee: CMPQ BX, AX
. . 10ca4f1: JGE 0x10ca600
. . 10ca4f7: MOVQ AX, 0x60(SP)
. . 10ca4fc: MOVQ CX, 0x50(SP) ;graph.go:106
. . 10ca501: LEAQ 0(AX)(AX*2), CX ;graph.go:104
. . 10ca505: MOVQ CX, 0x90(SP)
. . 10ca50d: MOVQ 0x10(SI)(CX*8), DX
20ms 20ms 10ca512: MOVQ DX, 0x70(SP) ;main.(*Graph).buildAdjList graph.go:104
. . 10ca517: MOVQ 0x8(SI)(CX*8), BX ;graph.go:104
. . 10ca51c: MOVQ BX, 0x68(SP)
. . 10ca521: MOVQ 0(SI)(CX*8), SI
. . 10ca525: MOVQ SI, 0x98(SP)
. . 10ca52d: MOVQ 0xf0(SP), DI ;graph.go:105
. . 10ca535: MOVQ DI, 0(SP)
. . 10ca539: MOVQ SI, 0x8(SP)
. . 10ca53e: MOVQ BX, 0x10(SP)
. . 10ca543: MOVQ DX, 0x18(SP)
. 280ms 10ca548: CALL main.(*index).nearCount(SB) ;main.(*Graph).buildAdjList graph.go:105
. . 10ca54d: MOVQ 0x20(SP), AX ;graph.go:105
. . 10ca552: MOVQ AX, 0x78(SP)
. . 10ca557: LEAQ runtime.types+85760(SB), CX ;graph.go:107
. . 10ca55e: MOVQ CX, 0(SP)
. . 10ca562: MOVQ AX, 0x8(SP)
. . 10ca567: MOVQ AX, 0x10(SP)
. 180ms 10ca56c: CALL runtime.makeslice(SB) ;main.(*Graph).buildAdjList graph.go:107
. . 10ca571: MOVQ 0x18(SP), AX ;graph.go:107
. . 10ca576: MOVQ AX, 0xc0(SP)
. . 10ca57e: MOVQ 0xf0(SP), CX ;graph.go:108
. . 10ca586: MOVQ CX, 0(SP)
. . 10ca58a: MOVQ 0x98(SP), DX
. . 10ca592: MOVQ DX, 0x8(SP)
. . 10ca597: MOVQ 0x68(SP), BX
. . 10ca59c: MOVQ BX, 0x10(SP)
. . 10ca5a1: MOVQ 0x70(SP), SI
. . 10ca5a6: MOVQ SI, 0x18(SP)
. . 10ca5ab: MOVQ AX, 0x20(SP)
. . 10ca5b0: MOVQ 0x78(SP), DI
. . 10ca5b5: MOVQ DI, 0x28(SP)
. . 10ca5ba: MOVQ DI, 0x30(SP)
. 750ms 10ca5bf: CALL main.(*index).near(SB) ;main.(*Graph).buildAdjList graph.go:108
. . 10ca5c4: MOVQ 0x78(SP), AX ;graph.go:106
. . 10ca5c9: MOVQ 0x50(SP), CX
. . 10ca5ce: ADDQ AX, CX
. . 10ca5d1: MOVQ CX, 0x50(SP)
. . 10ca5d6: MOVQ 0x70(SP), DX ;graph.go:109
. . 10ca5db: MOVQ 0xe8(SP), BX
. . 10ca5e3: MOVQ 0x98(SP), SI
. . 10ca5eb: MOVQ 0x68(SP), DI
. . 10ca5f0: MOVQ 0xc0(SP), R8
. . 10ca5f8: XORL R9, R9
. . 10ca5fb: JMP 0x10ca27f
. . 10ca600: XORPS X0, X0 ;graph.go:116
. . 10ca603: CVTSI2SDQ CX, X0
. . 10ca608: XORPS X1, X1
. . 10ca60b: CVTSI2SDQ BX, X1
. . 10ca610: DIVSD X1, X0
. . 10ca614: MOVSD_XMM X0, 0(SP)
. . 10ca619: CALL runtime.convT64(SB)
. . 10ca61e: MOVQ 0x8(SP), AX
. . 10ca623: XORPS X0, X0
. . 10ca626: MOVUPS X0, 0xc8(SP)
. . 10ca62e: LEAQ runtime.types+84032(SB), CX
. . 10ca635: MOVQ CX, 0xc8(SP)
. . 10ca63d: MOVQ AX, 0xd0(SP)
. . 10ca645: MOVQ os.Stdout(SB), AX ;print.go:213
. . 10ca64c: LEAQ go.itab.*os.File,io.Writer(SB), CX
. . 10ca653: MOVQ CX, 0(SP)
. . 10ca657: MOVQ AX, 0x8(SP)
. . 10ca65c: LEAQ go.string.*+3228(SB), AX
. . 10ca663: MOVQ AX, 0x10(SP)
. . 10ca668: MOVQ $0xa, 0x18(SP)
. . 10ca671: LEAQ 0xc8(SP), AX
. . 10ca679: MOVQ AX, 0x20(SP)
. . 10ca67e: MOVQ $0x1, 0x28(SP)
. . 10ca687: MOVQ $0x1, 0x30(SP)
. . 10ca690: CALL fmt.Fprintf(SB)
. . 10ca695: MOVQ 0xd8(SP), BP
. . 10ca69d: ADDQ $0xe0, SP
. . 10ca6a4: RET
. . 10ca6a5: MOVQ BX, AX ;graph.go:112
. . 10ca6a8: CALL runtime.panicIndex(SB)
. . 10ca6ad: CALL runtime.panicIndex(SB) ;graph.go:111
. . 10ca6b2: MOVQ R10, AX ;graph.go:110
. . 10ca6b5: MOVQ R11, CX
. . 10ca6b8: CALL runtime.panicIndex(SB)
. . 10ca6bd: NOPL
. . 10ca6be: CALL runtime.morestack_noctxt(SB) ;graph.go:101
. . 10ca6c3: JMP main.(*Graph).buildAdjList(SB)
. . 10ca6c8: INT $0x3
. . 10ca6c9: INT $0x3
. . 10ca6ca: INT $0x3
. . 10ca6cb: INT $0x3
. . 10ca6cc: INT $0x3
. . 10ca6cd: INT $0x3
. . 10ca6ce: INT $0x3
ROUTINE ======================== main.(*index).add
30ms 460ms (flat, cum) 6.91% of Total
. . 10cbdc0: MOVQ GS:0x30, CX ;index.go:29
. . 10cbdc9: LEAQ -0x18(SP), AX
. . 10cbdce: CMPQ 0x10(CX), AX
. . 10cbdd2: JBE 0x10cc0c6
. . 10cbdd8: SUBQ $0x98, SP
. . 10cbddf: MOVQ BP, 0x90(SP)
. . 10cbde7: LEAQ 0x90(SP), BP
. . 10cbdef: MOVQ 0xa0(SP), BX ;index.go:32
. . 10cbdf7: MOVQ 0x38(BX), DX
. . 10cbdfb: MOVQ 0x28(BX), SI
. . 10cbdff: MOVQ 0xb8(SP), DI
. . 10cbe07: LEAQ -0x1(DI), CX
. . 10cbe0b: CMPQ DX, CX
. . 10cbe0e: JA 0x10cc0c0
. . 10cbe14: MOVQ CX, 0x58(SP)
. . 10cbe19: MOVQ DX, 0x50(SP)
. . 10cbe1e: MOVQ SI, 0x78(SP)
. . 10cbe23: MOVQ 0xb0(SP), R8 ;index.go:33
. . 10cbe2b: XORL AX, AX
. . 10cbe2d: JMP 0x10cbe82
. . 10cbe2f: LEAQ 0x1(R8), R10 ;index.go:39
. . 10cbe33: MOVQ R10, 0x8(BX)(SI*8)
. . 10cbe38: MOVQ 0xa8(SP), R10
. . 10cbe40: MOVQ R10, 0(R9)(R8*8)
. . 10cbe44: MOVQ 0x78(SP), R9 ;index.go:33
. . 10cbe49: MOVQ 0x50(SP), R11
. . 10cbe4e: MOVQ 0x58(SP), R12
. . 10cbe53: MOVQ 0xb8(SP), R13
. . 10cbe5b: MOVQ 0xb0(SP), R14
. . 10cbe63: MOVQ 0x68(SP), R15
. . 10cbe68: MOVQ R12, CX ;index.go:100
. . 10cbe6b: MOVQ R11, DX ;index.go:99
. . 10cbe6e: MOVQ 0xa0(SP), BX ;index.go:36
. . 10cbe76: MOVQ R9, SI ;index.go:100
. . 10cbe79: MOVQ R13, DI ;index.go:33
. . 10cbe7c: MOVQ R14, R8 ;index.go:101
. . 10cbe7f: MOVQ R15, AX ;index.go:33
. . 10cbe82: CMPQ DI, AX
. . 10cbe85: JGE 0x10cc093
. 10ms 10cbe8b: NOPL ;main.(*index).add index.go:34
. . 10cbe8c: CMPQ DX, AX ;index.go:99
. . 10cbe8f: JA 0x10cc0b8
. . 10cbe95: CMPQ CX, AX ;index.go:100
. . 10cbe98: JA 0x10cc0b3
. . 10cbe9e: MOVQ AX, 0x48(SP) ;index.go:33
. . 10cbea3: SUBQ AX, CX ;index.go:100
. . 10cbea6: MOVQ CX, 0x40(SP)
. . 10cbeab: SUBQ AX, DX
. . 10cbeae: NEGQ DX
. . 10cbeb1: SARQ $0x3f, DX
. . 10cbeb5: ANDQ AX, DX
. . 10cbeb8: ADDQ SI, DX
. . 10cbebb: MOVQ DX, 0x70(SP)
. . 10cbec0: CMPQ R8, SI ;index.go:101
. . 10cbec3: JE 0x10cbed8
. . 10cbec5: MOVQ SI, 0(SP)
. . 10cbec9: MOVQ R8, 0x8(SP)
. . 10cbece: MOVQ AX, 0x10(SP)
. 10ms 10cbed3: CALL runtime.memmove(SB) ;main.skipOneCopy index.go:101
. . 10cbed8: MOVQ 0x48(SP), AX ;index.go:102
. . 10cbedd: INCQ AX
. . 10cbee0: MOVQ AX, 0x68(SP)
. . 10cbee5: MOVQ 0xb8(SP), CX
. . 10cbeed: SUBQ AX, CX
. . 10cbef0: MOVQ 0x40(SP), BX
. . 10cbef5: CMPQ CX, BX
. . 10cbef8: CMOVG CX, BX
. . 10cbefc: MOVQ 0xc0(SP), CX
. . 10cbf04: SUBQ AX, CX
. . 10cbf07: NEGQ CX
. . 10cbf0a: SARQ $0x3f, CX
. . 10cbf0e: ANDQ AX, CX
. . 10cbf11: MOVQ 0xb0(SP), DI
. . 10cbf19: ADDQ DI, CX
. . 10cbf1c: MOVQ 0x70(SP), R8
. . 10cbf21: CMPQ R8, CX
. . 10cbf24: JNE 0x10cc07b
. . 10cbf2a: MOVQ 0xa0(SP), AX ;index.go:36
. . 10cbf32: MOVQ 0(AX), CX
. . 10cbf35: MOVQ 0x8(AX), DX
. . 10cbf39: MOVQ 0x20(CX), CX
. . 10cbf3d: MOVQ DX, 0(SP)
. . 10cbf41: CALL CX
. . 10cbf43: MOVQ 0xa0(SP), AX ;index.go:37
. . 10cbf4b: MOVQ 0(AX), CX
. . 10cbf4e: MOVQ 0x8(AX), DX
. . 10cbf52: MOVQ 0x40(CX), CX
. . 10cbf56: MOVQ DX, 0(SP)
. . 10cbf5a: MOVQ 0x78(SP), DX
. . 10cbf5f: MOVQ DX, 0x8(SP)
. . 10cbf64: MOVQ 0x58(SP), BX
. . 10cbf69: MOVQ BX, 0x10(SP)
. . 10cbf6e: MOVQ 0x50(SP), SI
. . 10cbf73: MOVQ SI, 0x18(SP)
. . 10cbf78: CALL CX
. . 10cbf7a: MOVQ 0xa0(SP), AX ;index.go:38
. . 10cbf82: MOVQ 0(AX), CX
. . 10cbf85: MOVQ 0x8(AX), DX
. . 10cbf89: MOVQ 0x38(CX), CX
. . 10cbf8d: MOVQ DX, 0(SP)
. 10ms 10cbf91: CALL CX ;main.(*index).add index.go:38
. . 10cbf93: MOVQ 0x8(SP), AX ;index.go:38
. . 10cbf98: MOVQ 0xa0(SP), CX
. . 10cbfa0: MOVQ 0x40(CX), DX
. . 10cbfa4: TESTQ DX, DX
. . 10cbfa7: JE 0x10cc0ae
. . 10cbfad: MOVQ DX, BX
. . 10cbfb0: XORL DX, DX
. . 10cbfb2: DIVQ BX
. . 10cbfb5: MOVQ 0x10(CX), BX ;index.go:39
. . 10cbfb9: MOVQ 0x18(CX), SI
. . 10cbfbd: CMPQ SI, DX
. . 10cbfc0: JAE 0x10cc0a3
. . 10cbfc6: LEAQ 0(DX)(DX*2), SI
. . 10cbfca: MOVQ 0x10(BX)(SI*8), DI
30ms 30ms 10cbfcf: MOVQ 0x8(BX)(SI*8), R8 ;main.(*index).add index.go:39
. . 10cbfd4: MOVQ 0(BX)(SI*8), R9 ;index.go:39
. . 10cbfd8: LEAQ 0x1(R8), R10
. . 10cbfdc: LEAQ 0(BX)(SI*8), R11
. . 10cbfe0: CMPQ DI, R10
. . 10cbfe3: JBE 0x10cbe2f
. . 10cbfe9: MOVQ BX, 0x88(SP)
. . 10cbff1: MOVQ SI, 0x60(SP)
. . 10cbff6: MOVQ R11, 0x80(SP)
. . 10cbffe: LEAQ runtime.types+85760(SB), AX
. . 10cc005: MOVQ AX, 0(SP)
. . 10cc009: MOVQ R9, 0x8(SP)
. . 10cc00e: MOVQ R8, 0x10(SP)
. . 10cc013: MOVQ DI, 0x18(SP)
. . 10cc018: MOVQ R10, 0x20(SP)
. 400ms 10cc01d: CALL runtime.growslice(SB) ;main.(*index).add index.go:39
. . 10cc022: MOVQ 0x28(SP), AX ;index.go:39
. . 10cc027: MOVQ 0x30(SP), CX
. . 10cc02c: MOVQ 0x38(SP), DX
. . 10cc031: MOVQ 0x60(SP), BX
. . 10cc036: MOVQ 0x88(SP), SI
. . 10cc03e: MOVQ DX, 0x10(SI)(BX*8)
. . 10cc043: CMPL $0x0, runtime.writeBarrier(SB)
. . 10cc04a: JNE 0x10cc06c
. . 10cc04c: MOVQ AX, 0(SI)(BX*8)
. . 10cc050: MOVQ CX, R8
. . 10cc053: MOVQ AX, R9
. . 10cc056: MOVQ 0xa0(SP), CX ;index.go:36
. . 10cc05e: MOVQ BX, DX ;index.go:39
. . 10cc061: MOVQ SI, BX
. . 10cc064: MOVQ DX, SI
. . 10cc067: JMP 0x10cbe2f
. . 10cc06c: MOVQ 0x80(SP), DI
. . 10cc074: CALL runtime.gcWriteBarrier(SB)
. . 10cc079: JMP 0x10cc050
. . 10cc07b: MOVQ R8, 0(SP) ;index.go:102
. . 10cc07f: MOVQ CX, 0x8(SP)
. . 10cc084: MOVQ BX, 0x10(SP)
. . 10cc089: CALL runtime.memmove(SB)
. . 10cc08e: JMP 0x10cbf2a
. . 10cc093: MOVQ 0x90(SP), BP
. . 10cc09b: ADDQ $0x98, SP
. . 10cc0a2: RET
. . 10cc0a3: MOVQ DX, AX ;index.go:39
. . 10cc0a6: MOVQ SI, CX
. . 10cc0a9: CALL runtime.panicIndexU(SB)
. . 10cc0ae: CALL runtime.panicdivide(SB) ;index.go:38
. . 10cc0b3: CALL runtime.panicSliceB(SB) ;index.go:100
. . 10cc0b8: MOVQ AX, CX ;index.go:99
. . 10cc0bb: CALL runtime.panicSliceAcap(SB)
. . 10cc0c0: CALL runtime.panicSliceAcap(SB) ;index.go:32
. . 10cc0c5: NOPL
. . 10cc0c6: CALL runtime.morestack_noctxt(SB) ;index.go:29
. . 10cc0cb: ?
. . 10cc0cc: LOCK CLD
. . 10cc0ce: ?
ROUTINE ======================== main.(*index).near
80ms 750ms (flat, cum) 11.26% of Total
. . 10cc3e0: MOVQ GS:0x30, CX ;index.go:77
. . 10cc3e9: LEAQ -0x8(SP), AX
. . 10cc3ee: CMPQ 0x10(CX), AX
. . 10cc3f2: JBE 0x10cc7f9
. . 10cc3f8: SUBQ $0x88, SP
. . 10cc3ff: MOVQ BP, 0x80(SP)
. . 10cc407: LEAQ 0x80(SP), BP
. . 10cc40f: MOVQ 0x90(SP), AX ;index.go:78
. . 10cc417: MOVQ 0(AX), CX
. . 10cc41a: MOVQ 0x8(AX), DX
. . 10cc41e: MOVQ 0x20(CX), CX
. . 10cc422: MOVQ DX, 0(SP)
. . 10cc426: CALL CX
. . 10cc428: MOVQ 0x90(SP), AX ;index.go:79
. . 10cc430: MOVQ 0(AX), CX
. . 10cc433: MOVQ 0x8(AX), DX
. . 10cc437: MOVQ 0x40(CX), CX
. . 10cc43b: MOVQ DX, 0(SP)
. . 10cc43f: MOVQ 0x98(SP), DX
. . 10cc447: MOVQ DX, 0x8(SP)
. . 10cc44c: MOVQ 0xa0(SP), BX
. . 10cc454: MOVQ BX, 0x10(SP)
. . 10cc459: MOVQ 0xa8(SP), SI
. . 10cc461: MOVQ SI, 0x18(SP)
. . 10cc466: CALL CX
. . 10cc468: MOVQ 0x90(SP), AX ;index.go:80
. . 10cc470: MOVQ 0(AX), CX
. . 10cc473: MOVQ 0x8(AX), DX
. . 10cc477: MOVQ 0x38(CX), CX
. . 10cc47b: MOVQ DX, 0(SP)
. . 10cc47f: CALL CX
. . 10cc481: MOVQ 0x8(SP), AX
. . 10cc486: MOVQ 0x90(SP), CX
. . 10cc48e: MOVQ 0x40(CX), DX
. . 10cc492: TESTQ DX, DX
. . 10cc495: JE 0x10cc7f3
. . 10cc49b: MOVQ DX, BX
. . 10cc49e: XORL DX, DX
. . 10cc4a0: DIVQ BX
. . 10cc4a3: MOVQ 0x10(CX), BX ;index.go:81
. . 10cc4a7: MOVQ 0x18(CX), SI
. . 10cc4ab: CMPQ SI, DX
. . 10cc4ae: JAE 0x10cc7e8
. . 10cc4b4: LEAQ 0(DX)(DX*2), SI
. . 10cc4b8: MOVQ 0x8(BX)(SI*8), DI
. . 10cc4bd: MOVQ 0xb8(SP), R8
. . 10cc4c5: CMPQ DI, R8
. . 10cc4c8: MOVQ R8, R9
. . 10cc4cb: CMOVG DI, R8
. . 10cc4cf: MOVQ 0(BX)(SI*8), BX
. . 10cc4d3: MOVQ 0xb0(SP), SI
. . 10cc4db: CMPQ SI, BX
. . 10cc4de: JNE 0x10cc77a
. . 10cc4e4: MOVQ 0x38(CX), DX ;index.go:83
. . 10cc4e8: MOVQ 0x28(CX), BX
. . 10cc4ec: MOVQ 0xa0(SP), DI
. . 10cc4f4: LEAQ -0x1(DI), R10
. . 10cc4f8: CMPQ DX, R10
. . 10cc4fb: JA 0x10cc7e0
. . 10cc501: MOVQ R10, 0x58(SP)
. . 10cc506: MOVQ DX, 0x48(SP)
. . 10cc50b: MOVQ BX, 0x78(SP)
. . 10cc510: MOVQ 0x98(SP), R11 ;index.go:84
. . 10cc518: XORL AX, AX
. . 10cc51a: JMP 0x10cc562
. . 10cc51c: MOVQ 0xa0(SP), R12
. . 10cc524: MOVQ 0x78(SP), R13
. . 10cc529: MOVQ 0x48(SP), R14
. . 10cc52e: MOVQ 0x58(SP), R15
. . 10cc533: MOVQ 0x98(SP), AX
. . 10cc53b: MOVQ 0x68(SP), DX
. . 10cc540: MOVQ R14, DX ;index.go:99
. . 10cc543: MOVQ R13, BX ;index.go:100
. . 10cc546: MOVQ R12, DI ;index.go:84
. . 10cc549: MOVQ R8, R9 ;index.go:91
. . 10cc54c: MOVQ R15, R10 ;index.go:100
. . 10cc54f: MOVQ AX, R11 ;index.go:101
. . 10cc552: MOVQ 0x68(SP), AX ;index.go:84
. . 10cc557: MOVQ SI, R8 ;index.go:91
. . 10cc55a: MOVQ 0xb0(SP), SI
. . 10cc562: CMPQ DI, AX ;index.go:84
. . 10cc565: JGE 0x10cc76a
. . 10cc56b: NOPL ;index.go:85
. . 10cc56c: CMPQ DX, AX ;index.go:99
. . 10cc56f: JA 0x10cc7d8
. . 10cc575: CMPQ R10, AX ;index.go:100
. . 10cc578: JA 0x10cc7d0
. . 10cc57e: MOVQ AX, 0x40(SP) ;index.go:84
. . 10cc583: MOVQ R8, 0x50(SP) ;index.go:91
. . 10cc588: SUBQ AX, R10 ;index.go:100
. . 10cc58b: MOVQ R10, 0x38(SP)
. . 10cc590: SUBQ AX, DX
. . 10cc593: NEGQ DX
. . 10cc596: SARQ $0x3f, DX
. . 10cc59a: ANDQ AX, DX
. . 10cc59d: ADDQ BX, DX
. . 10cc5a0: MOVQ DX, 0x70(SP)
. . 10cc5a5: CMPQ R11, BX ;index.go:101
. . 10cc5a8: JE 0x10cc5bd
. . 10cc5aa: MOVQ BX, 0(SP)
. . 10cc5ae: MOVQ R11, 0x8(SP)
. . 10cc5b3: MOVQ AX, 0x10(SP)
. . 10cc5b8: CALL runtime.memmove(SB)
. . 10cc5bd: MOVQ 0x40(SP), AX ;index.go:102
. . 10cc5c2: INCQ AX
. . 10cc5c5: MOVQ AX, 0x68(SP)
. . 10cc5ca: MOVQ 0xa0(SP), CX
. . 10cc5d2: SUBQ AX, CX
. . 10cc5d5: MOVQ 0x38(SP), BX
. . 10cc5da: CMPQ CX, BX
. . 10cc5dd: CMOVG CX, BX
. . 10cc5e1: MOVQ 0xa8(SP), CX
. . 10cc5e9: SUBQ AX, CX
. . 10cc5ec: NEGQ CX
. . 10cc5ef: SARQ $0x3f, CX
. . 10cc5f3: ANDQ AX, CX
. . 10cc5f6: MOVQ 0x98(SP), DI
. . 10cc5fe: ADDQ DI, CX
. . 10cc601: MOVQ 0x70(SP), R8
. . 10cc606: CMPQ R8, CX
. . 10cc609: JNE 0x10cc752
. . 10cc60f: MOVQ 0x90(SP), AX ;index.go:87
. . 10cc617: MOVQ 0(AX), CX
. . 10cc61a: MOVQ 0x8(AX), DX
. . 10cc61e: MOVQ 0x20(CX), CX
. . 10cc622: MOVQ DX, 0(SP)
. . 10cc626: CALL CX
. . 10cc628: MOVQ 0x90(SP), AX ;index.go:88
. . 10cc630: MOVQ 0(AX), CX
. . 10cc633: MOVQ 0x8(AX), DX
. . 10cc637: MOVQ 0x40(CX), CX
. . 10cc63b: MOVQ DX, 0(SP)
. . 10cc63f: MOVQ 0x78(SP), DX
. . 10cc644: MOVQ DX, 0x8(SP)
. . 10cc649: MOVQ 0x58(SP), BX
. . 10cc64e: MOVQ BX, 0x10(SP)
. . 10cc653: MOVQ 0x48(SP), SI
. . 10cc658: MOVQ SI, 0x18(SP)
. 20ms 10cc65d: CALL CX ;main.(*index).near index.go:88
. . 10cc65f: MOVQ 0x90(SP), AX ;index.go:89
. . 10cc667: MOVQ 0(AX), CX
. . 10cc66a: MOVQ 0x8(AX), DX
. . 10cc66e: MOVQ 0x38(CX), CX
. . 10cc672: MOVQ DX, 0(SP)
. 30ms 10cc676: CALL CX ;main.(*index).near index.go:89
. . 10cc678: MOVQ 0x8(SP), AX ;index.go:89
. . 10cc67d: MOVQ 0x90(SP), CX
. . 10cc685: MOVQ 0x40(CX), DX
. . 10cc689: TESTQ DX, DX
. . 10cc68c: JE 0x10cc7cb
. . 10cc692: MOVQ DX, BX
. . 10cc695: XORL DX, DX
. . 10cc697: DIVQ BX
50ms 50ms 10cc69a: MOVQ 0x10(CX), BX ;main.(*index).near index.go:90
. . 10cc69e: MOVQ 0x18(CX), SI ;index.go:90
. . 10cc6a2: CMPQ SI, DX
. . 10cc6a5: JAE 0x10cc7c0
. . 10cc6ab: LEAQ 0(DX)(DX*2), SI
. . 10cc6af: MOVQ 0(BX)(SI*8), DI
20ms 20ms 10cc6b3: MOVQ 0x8(BX)(SI*8), BX ;main.(*index).near index.go:90
. . 10cc6b8: MOVQ 0x50(SP), AX ;index.go:91
. . 10cc6bd: MOVQ 0xb8(SP), SI
. . 10cc6c5: CMPQ SI, AX
. . 10cc6c8: JA 0x10cc7b8
. . 10cc6ce: MOVQ SI, R8
. . 10cc6d1: SUBQ AX, SI
. . 10cc6d4: CMPQ BX, SI
. . 10cc6d7: CMOVG BX, SI
. . 10cc6db: MOVQ 0xc0(SP), BX
. . 10cc6e3: MOVQ BX, R9
. . 10cc6e6: SUBQ AX, BX
. . 10cc6e9: NEGQ BX
. . 10cc6ec: SHLQ $0x3, AX
. . 10cc6f0: SARQ $0x3f, BX
. . 10cc6f4: ANDQ BX, AX
. . 10cc6f7: MOVQ 0xb0(SP), BX
. . 10cc6ff: LEAQ 0(BX)(AX*1), R10
. . 10cc703: CMPQ DI, R10
. . 10cc706: JE 0x10cc51c
. . 10cc70c: MOVQ SI, 0x60(SP)
. . 10cc711: MOVQ R10, 0(SP)
. . 10cc715: MOVQ DI, 0x8(SP)
. . 10cc71a: SHLQ $0x3, SI
. . 10cc71e: MOVQ SI, 0x10(SP)
. 510ms 10cc723: CALL runtime.memmove(SB) ;main.(*index).near index.go:91
. . 10cc728: MOVQ 0x90(SP), CX ;index.go:87
10ms 10ms 10cc730: MOVQ 0xb0(SP), BX ;main.(*index).near index.go:91
. . 10cc738: MOVQ 0x60(SP), SI ;index.go:91
. . 10cc73d: MOVQ 0xb8(SP), R8
. . 10cc745: MOVQ 0xc0(SP), R9
. . 10cc74d: JMP 0x10cc51c
. . 10cc752: MOVQ R8, 0(SP) ;index.go:102
. . 10cc756: MOVQ CX, 0x8(SP)
. . 10cc75b: MOVQ BX, 0x10(SP)
. . 10cc760: CALL runtime.memmove(SB)
. . 10cc765: JMP 0x10cc60f
. . 10cc76a: MOVQ 0x80(SP), BP
. . 10cc772: ADDQ $0x88, SP
. . 10cc779: RET
. . 10cc77a: MOVQ R8, 0x50(SP) ;index.go:81
. . 10cc77f: MOVQ SI, 0(SP)
. . 10cc783: MOVQ BX, 0x8(SP)
. . 10cc788: SHLQ $0x3, R8
. . 10cc78c: MOVQ R8, 0x10(SP)
. 110ms 10cc791: CALL runtime.memmove(SB) ;main.(*index).near index.go:81
. . 10cc796: MOVQ 0x90(SP), CX ;index.go:83
. . 10cc79e: MOVQ 0xb0(SP), SI ;index.go:91
. . 10cc7a6: MOVQ 0x50(SP), R8
. . 10cc7ab: MOVQ 0xb8(SP), R9
. . 10cc7b3: JMP 0x10cc4e4 ;index.go:81
. . 10cc7b8: MOVQ SI, CX ;index.go:91
. . 10cc7bb: CALL runtime.panicSliceB(SB)
. . 10cc7c0: MOVQ DX, AX ;index.go:90
. . 10cc7c3: MOVQ SI, CX
. . 10cc7c6: CALL runtime.panicIndexU(SB)
. . 10cc7cb: CALL runtime.panicdivide(SB) ;index.go:89
. . 10cc7d0: MOVQ R10, CX ;index.go:100
. . 10cc7d3: CALL runtime.panicSliceB(SB)
. . 10cc7d8: MOVQ AX, CX ;index.go:99
. . 10cc7db: CALL runtime.panicSliceAcap(SB)
. . 10cc7e0: MOVQ R10, CX ;index.go:83
. . 10cc7e3: CALL runtime.panicSliceAcap(SB)
. . 10cc7e8: MOVQ DX, AX ;index.go:81
. . 10cc7eb: MOVQ SI, CX
. . 10cc7ee: CALL runtime.panicIndexU(SB)
. . 10cc7f3: CALL runtime.panicdivide(SB) ;index.go:80
. . 10cc7f8: NOPL
. . 10cc7f9: CALL runtime.morestack_noctxt(SB) ;index.go:77
. . 10cc7fe: JMP main.(*index).near(SB)
. . 10cc803: INT $0x3
. . 10cc804: INT $0x3
. . 10cc805: INT $0x3
. . 10cc806: INT $0x3
. . 10cc807: INT $0x3
. . 10cc808: INT $0x3
. . 10cc809: INT $0x3
. . 10cc80a: INT $0x3
. . 10cc80b: INT $0x3
. . 10cc80c: INT $0x3
. . 10cc80d: INT $0x3
. . 10cc80e: INT $0x3
ROUTINE ======================== main.(*index).nearCount
240ms 280ms (flat, cum) 4.20% of Total
. . 10cc0d0: MOVQ GS:0x30, CX ;index.go:56
. . 10cc0d9: CMPQ 0x10(CX), SP
. . 10cc0dd: JBE 0x10cc3c9
. . 10cc0e3: ADDQ $-0x80, SP
. . 10cc0e7: MOVQ BP, 0x78(SP)
. . 10cc0ec: LEAQ 0x78(SP), BP
. . 10cc0f1: MOVQ 0x88(SP), AX ;index.go:58
. . 10cc0f9: MOVQ 0(AX), CX
. . 10cc0fc: MOVQ 0x8(AX), DX
. . 10cc100: MOVQ 0x20(CX), CX
. . 10cc104: MOVQ DX, 0(SP)
. . 10cc108: CALL CX
. . 10cc10a: MOVQ 0x88(SP), AX ;index.go:59
. . 10cc112: MOVQ 0(AX), CX
. . 10cc115: MOVQ 0x8(AX), DX
. . 10cc119: MOVQ 0x40(CX), CX
. . 10cc11d: MOVQ DX, 0(SP)
. . 10cc121: MOVQ 0x90(SP), DX
. . 10cc129: MOVQ DX, 0x8(SP)
. . 10cc12e: MOVQ 0x98(SP), BX
. . 10cc136: MOVQ BX, 0x10(SP)
. . 10cc13b: MOVQ 0xa0(SP), SI
. . 10cc143: MOVQ SI, 0x18(SP)
. . 10cc148: CALL CX
. . 10cc14a: MOVQ 0x88(SP), AX ;index.go:60
. . 10cc152: MOVQ 0(AX), CX
. . 10cc155: MOVQ 0x8(AX), DX
. . 10cc159: MOVQ 0x38(CX), CX
. . 10cc15d: MOVQ DX, 0(SP)
. . 10cc161: CALL CX
. . 10cc163: MOVQ 0x8(SP), AX
. . 10cc168: MOVQ 0x88(SP), CX
. . 10cc170: MOVQ 0x40(CX), DX
. . 10cc174: TESTQ DX, DX
. . 10cc177: JE 0x10cc3c3
. . 10cc17d: MOVQ DX, BX
. . 10cc180: XORL DX, DX
. . 10cc182: DIVQ BX
. . 10cc185: MOVQ 0x10(CX), BX ;index.go:61
. . 10cc189: MOVQ 0x18(CX), SI
. . 10cc18d: CMPQ SI, DX
. . 10cc190: JAE 0x10cc3b8
. . 10cc196: LEAQ 0(DX)(DX*2), SI
. . 10cc19a: MOVQ 0x8(BX)(SI*8), BX
40ms 40ms 10cc19f: MOVQ 0x38(CX), DX ;main.(*index).nearCount index.go:63
. . 10cc1a3: MOVQ 0x28(CX), SI ;index.go:63
. . 10cc1a7: MOVQ 0x98(SP), DI
. . 10cc1af: LEAQ -0x1(DI), R8
. . 10cc1b3: CMPQ DX, R8
. . 10cc1b6: JA 0x10cc3b0
. . 10cc1bc: MOVQ R8, 0x50(SP)
. . 10cc1c1: MOVQ DX, 0x48(SP)
. . 10cc1c6: MOVQ SI, 0x70(SP)
. . 10cc1cb: MOVQ 0x90(SP), R9 ;index.go:64
. . 10cc1d3: XORL AX, AX
. . 10cc1d5: JMP 0x10cc21f
. . 10cc1d7: LEAQ 0(DX)(DX*2), R10 ;index.go:70
. . 10cc1db: MOVQ 0x8(SI)(R10*8), R10
150ms 150ms 10cc1e0: MOVQ 0x58(SP), R11 ;main.(*index).nearCount index.go:71
. . 10cc1e5: LEAQ 0(R11)(R10*1), BX ;index.go:71
10ms 10ms 10cc1e9: MOVQ 0x98(SP), R10 ;main.(*index).nearCount index.go:64
. . 10cc1f1: MOVQ 0x70(SP), R11 ;index.go:64
. . 10cc1f6: MOVQ 0x48(SP), R12
. . 10cc1fb: MOVQ 0x50(SP), R13
. . 10cc200: MOVQ 0x90(SP), R14
. . 10cc208: MOVQ 0x60(SP), R15
. . 10cc20d: MOVQ R12, DX ;index.go:99
. . 10cc210: MOVQ R11, SI ;index.go:100
. . 10cc213: MOVQ R10, DI ;index.go:64
. . 10cc216: MOVQ R13, R8 ;index.go:100
. . 10cc219: MOVQ R14, R9 ;index.go:101
. . 10cc21c: MOVQ R15, AX ;index.go:64
. . 10cc21f: CMPQ DI, AX
. . 10cc222: JGE 0x10cc37e
. . 10cc228: NOPL ;index.go:65
. . 10cc229: CMPQ DX, AX ;index.go:99
. . 10cc22c: JA 0x10cc3a8
. . 10cc232: CMPQ R8, AX ;index.go:100
. . 10cc235: JA 0x10cc3a0
. . 10cc23b: MOVQ AX, 0x40(SP) ;index.go:64
. . 10cc240: MOVQ BX, 0x58(SP) ;index.go:71
. . 10cc245: SUBQ AX, R8 ;index.go:100
. . 10cc248: MOVQ R8, 0x38(SP)
. . 10cc24d: SUBQ AX, DX
. . 10cc250: NEGQ DX
. . 10cc253: SARQ $0x3f, DX
. . 10cc257: ANDQ AX, DX
. . 10cc25a: ADDQ SI, DX
. . 10cc25d: MOVQ DX, 0x68(SP)
. . 10cc262: CMPQ R9, SI ;index.go:101
. . 10cc265: JE 0x10cc27a
. . 10cc267: MOVQ SI, 0(SP)
. . 10cc26b: MOVQ R9, 0x8(SP)
. . 10cc270: MOVQ AX, 0x10(SP)
. . 10cc275: CALL runtime.memmove(SB)
. . 10cc27a: MOVQ 0x40(SP), AX ;index.go:102
. . 10cc27f: INCQ AX
. . 10cc282: MOVQ AX, 0x60(SP)
. . 10cc287: MOVQ 0x98(SP), CX
. . 10cc28f: SUBQ AX, CX
. . 10cc292: MOVQ 0x38(SP), BX
. . 10cc297: CMPQ CX, BX
. . 10cc29a: CMOVG CX, BX
. . 10cc29e: MOVQ 0xa0(SP), CX
. . 10cc2a6: SUBQ AX, CX
. . 10cc2a9: NEGQ CX
. . 10cc2ac: SARQ $0x3f, CX
. . 10cc2b0: ANDQ AX, CX
. . 10cc2b3: MOVQ 0x90(SP), DI
. . 10cc2bb: ADDQ DI, CX
. . 10cc2be: MOVQ 0x68(SP), R8
. . 10cc2c3: CMPQ R8, CX
. . 10cc2c6: JNE 0x10cc366
. . 10cc2cc: MOVQ 0x88(SP), AX ;index.go:67
. . 10cc2d4: MOVQ 0(AX), CX
. . 10cc2d7: MOVQ 0x8(AX), DX
. . 10cc2db: MOVQ 0x20(CX), CX
. . 10cc2df: MOVQ DX, 0(SP)
. . 10cc2e3: CALL CX
. . 10cc2e5: MOVQ 0x88(SP), AX ;index.go:68
. . 10cc2ed: MOVQ 0(AX), CX
. . 10cc2f0: MOVQ 0x8(AX), DX
. . 10cc2f4: MOVQ 0x40(CX), CX
. . 10cc2f8: MOVQ DX, 0(SP)
. . 10cc2fc: MOVQ 0x70(SP), DX
. . 10cc301: MOVQ DX, 0x8(SP)
. . 10cc306: MOVQ 0x50(SP), BX
. . 10cc30b: MOVQ BX, 0x10(SP)
. . 10cc310: MOVQ 0x48(SP), SI
. . 10cc315: MOVQ SI, 0x18(SP)
. 20ms 10cc31a: CALL CX ;main.(*index).nearCount index.go:68
10ms 10ms 10cc31c: MOVQ 0x88(SP), AX ;main.(*index).nearCount index.go:69
. . 10cc324: MOVQ 0(AX), CX ;index.go:69
. . 10cc327: MOVQ 0x8(AX), DX
. . 10cc32b: MOVQ 0x38(CX), CX
. . 10cc32f: MOVQ DX, 0(SP)
. 20ms 10cc333: CALL CX ;main.(*index).nearCount index.go:69
. . 10cc335: MOVQ 0x8(SP), AX ;index.go:69
. . 10cc33a: MOVQ 0x88(SP), CX
. . 10cc342: MOVQ 0x40(CX), DX
. . 10cc346: TESTQ DX, DX
. . 10cc349: JE 0x10cc39b
. . 10cc34b: MOVQ DX, BX
. . 10cc34e: XORL DX, DX
. . 10cc350: DIVQ BX
30ms 30ms 10cc353: MOVQ 0x18(CX), BX ;main.(*index).nearCount index.go:70
. . 10cc357: MOVQ 0x10(CX), SI ;index.go:70
. . 10cc35b: CMPQ BX, DX
. . 10cc35e: JB 0x10cc1d7
. . 10cc364: JMP 0x10cc390
. . 10cc366: MOVQ R8, 0(SP) ;index.go:102
. . 10cc36a: MOVQ CX, 0x8(SP)
. . 10cc36f: MOVQ BX, 0x10(SP)
. . 10cc374: CALL runtime.memmove(SB)
. . 10cc379: JMP 0x10cc2cc
. . 10cc37e: MOVQ BX, 0xa8(SP) ;index.go:74
. . 10cc386: MOVQ 0x78(SP), BP
. . 10cc38b: SUBQ $-0x80, SP
. . 10cc38f: RET
. . 10cc390: MOVQ DX, AX ;index.go:70
. . 10cc393: MOVQ BX, CX
. . 10cc396: CALL runtime.panicIndexU(SB)
. . 10cc39b: CALL runtime.panicdivide(SB) ;index.go:69
. . 10cc3a0: MOVQ R8, CX ;index.go:100
. . 10cc3a3: CALL runtime.panicSliceB(SB)
. . 10cc3a8: MOVQ AX, CX ;index.go:99
. . 10cc3ab: CALL runtime.panicSliceAcap(SB)
. . 10cc3b0: MOVQ R8, CX ;index.go:63
. . 10cc3b3: CALL runtime.panicSliceAcap(SB)
. . 10cc3b8: MOVQ DX, AX ;index.go:61
. . 10cc3bb: MOVQ SI, CX
. . 10cc3be: CALL runtime.panicIndexU(SB)
. . 10cc3c3: CALL runtime.panicdivide(SB) ;index.go:60
. . 10cc3c8: NOPL
. . 10cc3c9: CALL runtime.morestack_noctxt(SB) ;index.go:56
. . 10cc3ce: JMP main.(*index).nearCount(SB)
. . 10cc3d3: INT $0x3
. . 10cc3d4: INT $0x3
. . 10cc3d5: INT $0x3
. . 10cc3d6: INT $0x3
. . 10cc3d7: INT $0x3
. . 10cc3d8: INT $0x3
. . 10cc3d9: INT $0x3
. . 10cc3da: INT $0x3
. . 10cc3db: INT $0x3
. . 10cc3dc: INT $0x3
. . 10cc3dd: INT $0x3
. . 10cc3de: INT $0x3
ROUTINE ======================== main.LoadDictionary
50ms 3.32s (flat, cum) 49.85% of Total
. . 10c9ab0: MOVQ GS:0x30, CX ;graph.go:39
. . 10c9ab9: LEAQ 0xfffffec0(SP), AX
. . 10c9ac1: CMPQ 0x10(CX), AX
. . 10c9ac5: JBE 0x10ca1ef
. . 10c9acb: SUBQ $0x1c0, SP
. . 10c9ad2: MOVQ BP, 0x1b8(SP)
. . 10c9ada: LEAQ 0x1b8(SP), BP
. . 10c9ae2: MOVQ $0x0, 0x1f0(SP)
. . 10c9aee: LEAQ go.string.*+5959(SB), AX ;graph.go:40
. . 10c9af5: MOVQ AX, 0(SP)
. . 10c9af9: MOVQ $0xe, 0x8(SP)
. . 10c9b02: CALL main.newTimer(SB)
. . 10c9b07: MOVQ 0x10(SP), AX
. . 10c9b0c: MOVL $0x0, 0x68(SP)
. . 10c9b14: MOVQ AX, 0x80(SP)
. . 10c9b1c: LEAQ 0x68(SP), AX
. . 10c9b21: MOVQ AX, 0(SP)
. . 10c9b25: CALL runtime.deferprocStack(SB)
. . 10c9b2a: TESTL AX, AX
. . 10c9b2c: JNE 0x10ca1d0
. . 10c9b32: NOPL ;graph.go:41
. . 10c9b33: MOVQ 0x1c8(SP), AX ;file.go:280
. . 10c9b3b: MOVQ AX, 0(SP)
. . 10c9b3f: MOVQ 0x1d0(SP), AX
. . 10c9b47: MOVQ AX, 0x8(SP)
. . 10c9b4c: MOVQ $0x0, 0x10(SP)
. . 10c9b55: MOVL $0x0, 0x18(SP)
. . 10c9b5d: CALL os.OpenFile(SB)
. . 10c9b62: MOVQ 0x20(SP), AX
. . 10c9b67: MOVQ AX, 0x118(SP)
. . 10c9b6f: MOVQ 0x30(SP), CX
. . 10c9b74: MOVQ 0x28(SP), DX
. . 10c9b79: TESTQ DX, DX ;graph.go:42
. . 10c9b7c: JE 0x10c9bc2
. . 10c9b7e: JE 0x10c9b84 ;graph.go:43
. . 10c9b80: MOVQ 0x8(DX), DX
. . 10c9b84: XORPS X0, X0
. . 10c9b87: MOVUPS X0, 0x128(SP)
. . 10c9b8f: MOVQ DX, 0x128(SP)
. . 10c9b97: MOVQ CX, 0x130(SP)
. . 10c9b9f: LEAQ 0x128(SP), AX
. . 10c9ba7: MOVQ AX, 0(SP)
. . 10c9bab: MOVQ $0x1, 0x8(SP)
. . 10c9bb4: MOVQ $0x1, 0x10(SP)
. . 10c9bbd: CALL log.Fatal(SB)
. . 10c9bc2: MOVL $0x18, 0xa0(SP) ;graph.go:45
. . 10c9bcd: LEAQ go.func.*+293(SB), AX
. . 10c9bd4: MOVQ AX, 0xb8(SP)
. . 10c9bdc: MOVQ 0x118(SP), AX
. . 10c9be4: MOVQ AX, 0xd0(SP)
. . 10c9bec: LEAQ 0xa0(SP), CX
. . 10c9bf4: MOVQ CX, 0(SP)
. . 10c9bf8: CALL runtime.deferprocStack(SB)
. . 10c9bfd: TESTL AX, AX
. . 10c9bff: JNE 0x10ca1ba
. . 10c9c05: LEAQ runtime.types+157184(SB), AX ;graph.go:47
. . 10c9c0c: MOVQ AX, 0(SP)
. . 10c9c10: CALL runtime.newobject(SB)
. . 10c9c15: MOVQ 0x8(SP), AX
. . 10c9c1a: MOVQ AX, 0x120(SP)
. . 10c9c22: LEAQ runtime.types+141472(SB), CX ;graph.go:48
. . 10c9c29: MOVQ CX, 0(SP)
. . 10c9c2d: XORPS X0, X0
. . 10c9c30: MOVUPS X0, 0x8(SP)
. . 10c9c35: CALL runtime.makeslice(SB)
. . 10c9c3a: MOVQ 0x18(SP), AX
. . 10c9c3f: CMPL $0x0, runtime.writeBarrier(SB) ;graph.go:47
. . 10c9c46: JNE 0x10ca175
. . 10c9c4c: XORPS X0, X0
. . 10c9c4f: MOVQ 0x120(SP), CX
. . 10c9c57: MOVUPS X0, 0(CX)
. . 10c9c5a: MOVUPS X0, 0x10(CX)
. . 10c9c5e: MOVUPS X0, 0x20(CX)
. . 10c9c62: MOVQ AX, 0(CX)
. . 10c9c65: NOPL ;graph.go:53
. . 10c9c66: LEAQ 0x138(SP), DI ;scan.go:87
. . 10c9c6e: MOVQ BP, -0x10(SP)
. . 10c9c73: LEAQ -0x10(SP), BP
. . 10c9c78: CALL 0x10586ba
. . 10c9c7d: MOVQ 0(BP), BP
. . 10c9c81: LEAQ 0x138(SP), DI
. . 10c9c89: MOVQ BP, -0x10(SP)
. . 10c9c8e: LEAQ -0x10(SP), BP
. . 10c9c93: CALL 0x10586ba
. . 10c9c98: MOVQ 0(BP), BP
. . 10c9c9c: LEAQ go.itab.*os.File,io.Reader(SB), AX
. . 10c9ca3: MOVQ AX, 0x138(SP)
. . 10c9cab: MOVQ 0x118(SP), AX
. . 10c9cb3: MOVQ AX, 0x140(SP)
. . 10c9cbb: LEAQ go.func.*+5(SB), AX
. . 10c9cc2: MOVQ AX, 0x148(SP)
. . 10c9cca: MOVQ $0x10000, 0x150(SP)
. . 10c9cd6: XORL AX, AX
. . 10c9cd8: JMP 0x10c9cdd ;graph.go:54
. . 10c9cda: MOVQ SI, AX ;graph.go:74
. . 10c9cdd: MOVQ AX, 0x48(SP)
. . 10c9ce2: LEAQ 0x138(SP), CX ;graph.go:54
. . 10c9cea: MOVQ CX, 0(SP)
. 20ms 10c9cee: CALL bufio.(*Scanner).Scan(SB) ;main.LoadDictionary graph.go:54
. . 10c9cf3: CMPB $0x0, 0x8(SP) ;graph.go:54
. . 10c9cf8: JE 0x10c9e3b
. . 10c9cfe: NOPL ;graph.go:55
. . 10c9cff: MOVQ 0x160(SP), AX ;scan.go:106
. . 10c9d07: MOVQ AX, 0x40(SP)
. . 10c9d0c: MOVQ 0x158(SP), CX
. . 10c9d14: MOVQ CX, 0x100(SP)
. . 10c9d1c: LEAQ runtime.types+88768(SB), DX ;graph.go:56
. . 10c9d23: MOVQ DX, 0(SP)
. . 10c9d27: MOVQ AX, 0x8(SP)
. . 10c9d2c: MOVQ AX, 0x10(SP)
. . 10c9d31: CALL runtime.makeslice(SB)
. . 10c9d36: MOVQ 0x18(SP), AX
. . 10c9d3b: MOVQ AX, 0x110(SP)
. . 10c9d43: MOVQ 0x100(SP), CX ;graph.go:57
. . 10c9d4b: CMPQ CX, AX
. . 10c9d4e: JE 0x10c9d68
. . 10c9d50: MOVQ AX, 0(SP)
. . 10c9d54: MOVQ CX, 0x8(SP)
. . 10c9d59: MOVQ 0x40(SP), CX
. . 10c9d5e: MOVQ CX, 0x10(SP)
. . 10c9d63: CALL runtime.memmove(SB)
. . 10c9d68: MOVQ 0x120(SP), CX ;graph.go:58
. . 10c9d70: MOVQ 0x8(CX), DX
. . 10c9d74: MOVQ 0x10(CX), BX
. . 10c9d78: LEAQ 0x1(DX), SI
. . 10c9d7c: MOVQ 0(CX), R8
. . 10c9d7f: CMPQ BX, SI
. . 10c9d82: JA 0x10c9ddb
. . 10c9d84: LEAQ 0x1(DX), BX
. . 10c9d88: MOVQ BX, 0x8(CX)
. . 10c9d8c: LEAQ 0(DX)(DX*2), DX
. . 10c9d90: MOVQ 0x40(SP), BX
10ms 10ms 10c9d95: MOVQ BX, 0x8(R8)(DX*8) ;main.LoadDictionary graph.go:58
20ms 20ms 10c9d9a: MOVQ BX, 0x10(R8)(DX*8)
. . 10c9d9f: MOVQ 0x48(SP), SI ;graph.go:59
. . 10c9da4: CMPQ SI, BX
. . 10c9da7: CMOVG BX, SI ;graph.go:74
. . 10c9dab: LEAQ 0(R8)(DX*8), DI ;graph.go:58
. . 10c9daf: CMPL $0x0, runtime.writeBarrier(SB)
. . 10c9db6: JNE 0x10c9dc9
. . 10c9db8: MOVQ 0x110(SP), AX
. . 10c9dc0: MOVQ AX, 0(R8)(DX*8)
. . 10c9dc4: JMP 0x10c9cda
. . 10c9dc9: MOVQ 0x110(SP), AX
. . 10c9dd1: CALL runtime.gcWriteBarrier(SB)
. . 10c9dd6: JMP 0x10c9cda
. . 10c9ddb: LEAQ runtime.types+141472(SB), AX
. . 10c9de2: MOVQ AX, 0(SP)
. . 10c9de6: MOVQ R8, 0x8(SP)
. . 10c9deb: MOVQ DX, 0x10(SP)
. . 10c9df0: MOVQ BX, 0x18(SP)
. . 10c9df5: MOVQ SI, 0x20(SP)
. 80ms 10c9dfa: CALL runtime.growslice(SB) ;main.LoadDictionary graph.go:58
. . 10c9dff: MOVQ 0x28(SP), AX ;graph.go:58
. . 10c9e04: MOVQ 0x30(SP), CX
. . 10c9e09: MOVQ 0x38(SP), DX
. . 10c9e0e: MOVQ 0x120(SP), DI
. . 10c9e16: MOVQ DX, 0x10(DI)
. . 10c9e1a: CMPL $0x0, runtime.writeBarrier(SB)
. . 10c9e21: JNE 0x10c9e34
. . 10c9e23: MOVQ AX, 0(DI)
. . 10c9e26: MOVQ CX, DX
. . 10c9e29: MOVQ AX, R8
. . 10c9e2c: MOVQ DI, CX
. . 10c9e2f: JMP 0x10c9d84
. . 10c9e34: CALL runtime.gcWriteBarrier(SB)
. . 10c9e39: JMP 0x10c9e26
. . 10c9e3b: MOVQ 0x1e8(SP), AX ;graph.go:64
. . 10c9e43: TESTQ AX, AX
. . 10c9e46: JNE 0x10ca117
. . 10c9e4c: MOVQ 0x120(SP), AX ;graph.go:68
. . 10c9e54: MOVQ 0x8(AX), CX
. . 10c9e58: MOVQ CX, 0x60(SP)
. . 10c9e5d: LEAQ runtime.types+77120(SB), DX
. . 10c9e64: MOVQ DX, 0(SP)
. . 10c9e68: MOVQ CX, 0x8(SP)
. . 10c9e6d: MOVQ CX, 0x10(SP)
. . 10c9e72: CALL runtime.makeslice(SB)
. . 10c9e77: MOVQ 0x18(SP), AX
. . 10c9e7c: MOVQ 0x60(SP), CX
. . 10c9e81: MOVQ 0x120(SP), DX
. . 10c9e89: MOVQ CX, 0x20(DX)
. . 10c9e8d: MOVQ CX, 0x28(DX)
. . 10c9e91: CMPL $0x0, runtime.writeBarrier(SB)
. . 10c9e98: JNE 0x10ca109
. . 10c9e9e: MOVQ AX, 0x18(DX)
. . 10c9ea2: XORL AX, AX
. . 10c9ea4: JMP 0x10c9eb5 ;graph.go:69
. . 10c9ea6: LEAQ 0x1(SI), BX
. . 10c9eaa: MOVQ 0x60(SP), CX
. . 10c9eaf: MOVQ AX, DX ;graph.go:70
. . 10c9eb2: MOVQ BX, AX ;graph.go:69
. . 10c9eb5: CMPQ CX, AX
. . 10c9eb8: JGE 0x10c9f36
. . 10c9eba: MOVQ AX, 0x50(SP)
. . 10c9ebf: LEAQ runtime.types+85760(SB), AX ;graph.go:70
. . 10c9ec6: MOVQ AX, 0(SP)
. . 10c9eca: XORPS X0, X0
. . 10c9ecd: MOVUPS X0, 0x8(SP)
. . 10c9ed2: CALL runtime.makeslice(SB)
. . 10c9ed7: MOVQ 0x120(SP), AX
. . 10c9edf: MOVQ 0x20(AX), CX
. . 10c9ee3: MOVQ 0x18(AX), DX
. . 10c9ee7: MOVQ 0x18(SP), BX
. . 10c9eec: MOVQ 0x50(SP), SI
. . 10c9ef1: CMPQ CX, SI
. . 10c9ef4: JAE 0x10ca1e6
. . 10c9efa: LEAQ 0(SI)(SI*2), CX
10ms 10ms 10c9efe: MOVQ $0x0, 0x8(DX)(CX*8) ;main.LoadDictionary graph.go:70
10ms 10ms 10c9f07: MOVQ $0x0, 0x10(DX)(CX*8)
. . 10c9f10: LEAQ 0(DX)(CX*8), DI ;graph.go:70
. . 10c9f14: CMPL $0x0, runtime.writeBarrier(SB)
. . 10c9f1b: JNE 0x10c9f23
. . 10c9f1d: MOVQ BX, 0(DX)(CX*8)
. . 10c9f21: JMP 0x10c9ea6
. . 10c9f23: MOVQ AX, CX ;graph.go:47
. . 10c9f26: MOVQ BX, AX ;graph.go:70
. . 10c9f29: CALL runtime.gcWriteBarrier(SB)
. . 10c9f2e: MOVQ CX, AX
. . 10c9f31: JMP 0x10c9ea6
. . 10c9f36: LEAQ go.string.*+3388(SB), AX ;graph.go:73
. . 10c9f3d: MOVQ AX, 0(SP)
. . 10c9f41: MOVQ $0xa, 0x8(SP)
. . 10c9f4a: CALL main.newTimer(SB)
. . 10c9f4f: MOVQ 0x10(SP), AX
. . 10c9f54: MOVQ AX, 0xe8(SP)
. . 10c9f5c: MOVQ $0x800000, 0(SP) ;graph.go:74
. . 10c9f64: MOVQ 0x48(SP), CX
. . 10c9f69: MOVQ CX, 0x8(SP)
. 120ms 10c9f6e: CALL main.newIndex(SB) ;main.LoadDictionary graph.go:74
. . 10c9f73: MOVQ 0x10(SP), AX ;graph.go:74
. . 10c9f78: MOVQ AX, 0xf8(SP)
. . 10c9f80: MOVQ 0x120(SP), CX ;graph.go:75
. . 10c9f88: MOVQ 0x8(CX), DX
. . 10c9f8c: MOVQ 0(CX), BX
. . 10c9f8f: TESTQ DX, DX
. . 10c9f92: JLE 0x10c9ffb
. . 10c9f94: MOVQ DX, 0x60(SP)
. . 10c9f99: XORL SI, SI
. . 10c9f9b: JMP 0x10c9fb4
. . 10c9f9d: MOVQ 0x108(SP), DX
. . 10c9fa5: LEAQ 0x18(DX), BX
. . 10c9fa9: MOVQ AX, SI
. . 10c9fac: MOVQ 0xf8(SP), AX ;graph.go:76
. . 10c9fb4: MOVQ BX, 0x108(SP) ;graph.go:75
. . 10c9fbc: MOVQ SI, 0x58(SP)
. . 10c9fc1: MOVQ 0x10(BX), CX
. . 10c9fc5: MOVQ 0x8(BX), DX
. . 10c9fc9: MOVQ 0(BX), DI
. . 10c9fcc: MOVQ AX, 0(SP) ;graph.go:76
. . 10c9fd0: MOVQ SI, 0x8(SP)
. . 10c9fd5: MOVQ DI, 0x10(SP)
. . 10c9fda: MOVQ DX, 0x18(SP)
. . 10c9fdf: MOVQ CX, 0x20(SP)
. 450ms 10c9fe4: CALL main.(*index).add(SB) ;main.LoadDictionary graph.go:76
. . 10c9fe9: MOVQ 0x58(SP), AX ;graph.go:75
. . 10c9fee: INCQ AX
. . 10c9ff1: MOVQ 0x60(SP), CX
. . 10c9ff6: CMPQ CX, AX
. . 10c9ff9: JL 0x10c9f9d
. . 10c9ffb: MOVQ 0xe8(SP), DX ;graph.go:78
. . 10ca003: MOVQ 0(DX), AX
. . 10ca006: CALL AX
. . 10ca008: LEAQ go.string.*+4694(SB), AX ;graph.go:86
. . 10ca00f: MOVQ AX, 0(SP)
. . 10ca013: MOVQ $0xc, 0x8(SP)
. . 10ca01c: CALL main.newTimer(SB)
. . 10ca021: MOVQ 0x10(SP), AX
. . 10ca026: MOVQ AX, 0xf0(SP)
. . 10ca02e: MOVQ 0x120(SP), CX ;graph.go:87
. . 10ca036: MOVQ CX, 0(SP)
. . 10ca03a: MOVQ 0xf8(SP), BX
. . 10ca042: MOVQ BX, 0x8(SP)
. 2.60s 10ca047: CALL main.(*Graph).buildAdjList(SB) ;main.LoadDictionary graph.go:87
. . 10ca04c: MOVQ 0xf0(SP), DX ;graph.go:88
. . 10ca054: MOVQ 0(DX), AX
. . 10ca057: CALL AX
. . 10ca059: MOVQ 0x1e8(SP), AX ;graph.go:64
. . 10ca061: TESTQ AX, AX
. . 10ca064: JNE 0x10ca0ab ;graph.go:90
. . 10ca066: MOVZX 0x1d8(SP), AX ;graph.go:39
. . 10ca06e: TESTL AL, AL
. . 10ca070: JNE 0x10ca098 ;graph.go:94
. . 10ca072: MOVQ 0x120(SP), AX ;graph.go:98
. . 10ca07a: MOVQ AX, 0x1f0(SP)
. . 10ca082: NOPL
. . 10ca083: CALL runtime.deferreturn(SB)
. . 10ca088: MOVQ 0x1b8(SP), BP
. . 10ca090: ADDQ $0x1c0, SP
. . 10ca097: RET
. . 10ca098: MOVQ 0x120(SP), AX ;graph.go:95
. . 10ca0a0: MOVQ AX, 0(SP)
. . 10ca0a4: CALL main.adjListStats(SB)
. . 10ca0a9: JMP 0x10ca072
. . 10ca0ab: MOVQ $0x0, 0(SP) ;graph.go:91
. . 10ca0b3: MOVQ 0x1e0(SP), CX
. . 10ca0bb: MOVQ CX, 0x8(SP)
. . 10ca0c0: MOVQ AX, 0x10(SP)
. . 10ca0c5: LEAQ go.string.*+2067(SB), AX
. . 10ca0cc: MOVQ AX, 0x18(SP)
. . 10ca0d1: MOVQ $0x8, 0x20(SP)
. . 10ca0da: CALL runtime.concatstring2(SB)
. . 10ca0df: MOVQ 0x30(SP), AX
. . 10ca0e4: MOVQ 0x28(SP), CX
. . 10ca0e9: MOVQ 0x120(SP), DX
. . 10ca0f1: MOVQ DX, 0(SP)
. . 10ca0f5: MOVQ CX, 0x8(SP)
. . 10ca0fa: MOVQ AX, 0x10(SP)
. . 10ca0ff: CALL main.(*Graph).dumpAdjList(SB)
. . 10ca104: JMP 0x10ca066
. . 10ca109: LEAQ 0x18(DX), DI ;graph.go:68
. . 10ca10d: CALL runtime.gcWriteBarrier(SB)
. . 10ca112: JMP 0x10c9ea2
. . 10ca117: MOVQ $0x0, 0(SP) ;graph.go:65
. . 10ca11f: MOVQ 0x1e0(SP), CX
. . 10ca127: MOVQ CX, 0x8(SP)
. . 10ca12c: MOVQ AX, 0x10(SP)
. . 10ca131: LEAQ go.string.*+5334(SB), DX
. . 10ca138: MOVQ DX, 0x18(SP)
. . 10ca13d: MOVQ $0xd, 0x20(SP)
. . 10ca146: CALL runtime.concatstring2(SB)
. . 10ca14b: MOVQ 0x30(SP), AX
. . 10ca150: MOVQ 0x28(SP), CX
. . 10ca155: MOVQ 0x120(SP), DX
. . 10ca15d: MOVQ DX, 0(SP)
. . 10ca161: MOVQ CX, 0x8(SP)
. . 10ca166: MOVQ AX, 0x10(SP)
. . 10ca16b: CALL main.(*Graph).dumpVertices(SB)
. . 10ca170: JMP 0x10c9e4c
. . 10ca175: MOVQ AX, 0x110(SP) ;graph.go:48
. . 10ca17d: LEAQ runtime.types+157184(SB), AX ;graph.go:47
. . 10ca184: MOVQ AX, 0(SP)
. . 10ca188: MOVQ 0x120(SP), AX
. . 10ca190: MOVQ AX, 0x8(SP)
. . 10ca195: CALL runtime.typedmemclr(SB)
. . 10ca19a: MOVQ 0x120(SP), DI
. . 10ca1a2: MOVQ 0x110(SP), AX
. . 10ca1aa: CALL runtime.gcWriteBarrier(SB)
. . 10ca1af: MOVQ DI, CX ;graph.go:68
. . 10ca1b2: XORPS X0, X0 ;graph.go:48
. . 10ca1b5: JMP 0x10c9c65 ;graph.go:47
. . 10ca1ba: NOPL ;graph.go:45
. . 10ca1bb: CALL runtime.deferreturn(SB)
. . 10ca1c0: MOVQ 0x1b8(SP), BP
. . 10ca1c8: ADDQ $0x1c0, SP
. . 10ca1cf: RET
. . 10ca1d0: NOPL ;graph.go:40
. . 10ca1d1: CALL runtime.deferreturn(SB)
. . 10ca1d6: MOVQ 0x1b8(SP), BP
. . 10ca1de: ADDQ $0x1c0, SP
. . 10ca1e5: RET
. . 10ca1e6: MOVQ SI, AX ;graph.go:70
. . 10ca1e9: CALL runtime.panicIndex(SB)
. . 10ca1ee: NOPL
. . 10ca1ef: CALL runtime.morestack_noctxt(SB) ;graph.go:39
. . 10ca1f4: JMP main.LoadDictionary(SB)
. . 10ca1f9: INT $0x3
. . 10ca1fa: INT $0x3
. . 10ca1fb: INT $0x3
. . 10ca1fc: INT $0x3
. . 10ca1fd: INT $0x3
. . 10ca1fe: INT $0x3
ROUTINE ======================== main.distance
120ms 120ms (flat, cum) 1.80% of Total
. . 10cae60: SUBQ $0x18, SP ;graph.go:283
. . 10cae64: MOVQ BP, 0x10(SP)
. . 10cae69: LEAQ 0x10(SP), BP
. . 10cae6e: MOVQ 0x28(SP), CX ;graph.go:289
. . 10cae73: MOVQ 0x40(SP), DX
. . 10cae78: CMPQ DX, CX
. . 10cae7b: MOVQ CX, BX ;graph.go:292
. . 10cae7e: CMOVG DX, CX
. . 10cae82: MOVQ BX, SI ;graph.go:284
. . 10cae85: SUBQ DX, BX
10ms 10ms 10cae88: MOVQ DX, DI ;main.distance graph.go:286
. . 10cae8b: SUBQ SI, DX ;graph.go:286
. . 10cae8e: TESTQ BX, BX ;graph.go:285
. . 10cae91: CMOVL DX, BX ;graph.go:294
. . 10cae95: MOVQ 0x38(SP), DX ;graph.go:285
. . 10cae9a: MOVQ 0x20(SP), R8
. . 10cae9f: XORL AX, AX
. . 10caea1: JMP 0x10caeb6
. . 10caea3: MOVZX 0(DX)(AX*1), R10 ;graph.go:293
70ms 70ms 10caea8: LEAQ 0x1(BX), R11 ;main.distance graph.go:294
20ms 20ms 10caeac: CMPL R10, R9 ;main.distance graph.go:293
20ms 20ms 10caeaf: CMOVNE R11, BX ;main.distance graph.go:294
. . 10caeb3: INCQ AX ;graph.go:292
. . 10caeb6: CMPQ CX, AX
. . 10caeb9: JGE 0x10caecc
. . 10caebb: CMPQ SI, AX ;graph.go:293
. . 10caebe: JAE 0x10caee3
. . 10caec0: MOVZX 0(R8)(AX*1), R9
. . 10caec5: CMPQ DI, AX
. . 10caec8: JB 0x10caea3
. . 10caeca: JMP 0x10caedb
. . 10caecc: MOVQ BX, 0x50(SP) ;graph.go:298
. . 10caed1: MOVQ 0x10(SP), BP
. . 10caed6: ADDQ $0x18, SP
. . 10caeda: RET
. . 10caedb: MOVQ DI, CX ;graph.go:293
. . 10caede: CALL runtime.panicIndex(SB)
. . 10caee3: MOVQ SI, CX
. . 10caee6: CALL runtime.panicIndex(SB)
. . 10caeeb: NOPL
. . 10caeec: INT $0x3
. . 10caeed: INT $0x3
. . 10caeee: INT $0x3
ROUTINE ======================== main.main
0 3.32s (flat, cum) 49.85% of Total
. . 10cc810: MOVQ GS:0x30, CX ;main.go:24
. . 10cc819: LEAQ 0xfffffd98(SP), AX
. . 10cc821: CMPQ 0x10(CX), AX
. . 10cc825: JBE 0x10cd50f
. . 10cc82b: SUBQ $0x2e8, SP
. . 10cc832: MOVQ BP, 0x2e0(SP)
. . 10cc83a: LEAQ 0x2e0(SP), BP
. . 10cc842: MOVQ os.Args+8(SB), CX ;main.go:25
. . 10cc849: MOVQ os.Args(SB), DX ;flag.go:996
. . 10cc850: MOVQ os.Args+16(SB), BX
. . 10cc857: CMPQ $0x1, CX
. . 10cc85b: JB 0x10cd504
. . 10cc861: MOVQ flag.CommandLine(SB), AX
. . 10cc868: MOVQ AX, 0(SP)
. . 10cc86c: LEAQ -0x1(BX), AX
. . 10cc870: MOVQ AX, BX
. . 10cc873: NEGQ AX
. . 10cc876: SARQ $0x3f, AX
. . 10cc87a: ANDQ $0x10, AX
. . 10cc87e: ADDQ DX, AX
. . 10cc881: MOVQ AX, 0x8(SP)
. . 10cc886: LEAQ -0x1(CX), AX
. . 10cc88a: MOVQ AX, 0x10(SP)
. . 10cc88f: MOVQ BX, 0x18(SP)
. . 10cc894: CALL flag.(*FlagSet).Parse(SB)
. . 10cc899: MOVQ main.cpuprofile(SB), AX ;main.go:27
. . 10cc8a0: MOVQ 0(AX), CX
. . 10cc8a3: MOVQ 0x8(AX), AX
. . 10cc8a7: TESTQ AX, AX
. . 10cc8aa: JNE 0x10cd3a7
. . 10cc8b0: MOVQ main.traceprofile(SB), AX ;main.go:37
. . 10cc8b7: MOVQ 0(AX), CX
. . 10cc8ba: MOVQ 0x8(AX), AX
. . 10cc8be: TESTQ AX, AX
. . 10cc8c1: JNE 0x10cd245
. . 10cc8c7: MOVQ main.dump(SB), AX ;main.go:47
. . 10cc8ce: MOVQ 0x8(AX), CX
. . 10cc8d2: MOVQ 0(AX), AX
. . 10cc8d5: TESTQ CX, CX
. . 10cc8d8: JNE 0x10cd232
. . 10cc8de: XORPS X0, X0 ;main.go:51
. . 10cc8e1: MOVUPS X0, 0x250(SP)
. . 10cc8e9: LEAQ runtime.types+88448(SB), AX
. . 10cc8f0: MOVQ AX, 0x250(SP)
. . 10cc8f8: LEAQ internal/bytealg.IndexString.args_stackmap+640(SB), CX
. . 10cc8ff: MOVQ CX, 0x258(SP)
. . 10cc907: MOVQ os.Stdout(SB), CX ;print.go:274
. . 10cc90e: LEAQ go.itab.*os.File,io.Writer(SB), DX
. . 10cc915: MOVQ DX, 0(SP)
. . 10cc919: MOVQ CX, 0x8(SP)
. . 10cc91e: LEAQ 0x250(SP), CX
. . 10cc926: MOVQ CX, 0x10(SP)
. . 10cc92b: MOVQ $0x1, 0x18(SP)
. . 10cc934: MOVQ $0x1, 0x20(SP)
. . 10cc93d: CALL fmt.Fprintln(SB)
. . 10cc942: MOVQ main.dict(SB), AX ;main.go:52
. . 10cc949: MOVQ main.perfStats(SB), CX
. . 10cc950: MOVQ main.dump(SB), DX
. . 10cc957: MOVQ 0x8(AX), BX
. . 10cc95b: MOVQ 0(AX), AX
. . 10cc95e: MOVZX 0(CX), CX
. . 10cc961: MOVQ 0(DX), SI
. . 10cc964: MOVQ 0x8(DX), DX
. . 10cc968: MOVQ AX, 0(SP)
. . 10cc96c: MOVQ BX, 0x8(SP)
. . 10cc971: MOVB CL, 0x10(SP)
. . 10cc975: MOVQ SI, 0x18(SP)
. . 10cc97a: MOVQ DX, 0x20(SP)
. 3.32s 10cc97f: CALL main.LoadDictionary(SB) ;main.main main.go:52
. . 10cc984: MOVQ 0x28(SP), AX ;main.go:52
. . 10cc989: MOVQ AX, 0x1d0(SP)
. . 10cc991: MOVQ 0x8(AX), CX ;graph.go:303
. . 10cc995: MOVQ CX, 0x78(SP)
. . 10cc99a: MOVQ AX, 0(SP) ;main.go:53
. . 10cc99e: CALL main.(*Graph).EdgeCount(SB)
. . 10cc9a3: MOVQ 0x8(SP), AX
. . 10cc9a8: MOVQ AX, 0x70(SP)
. . 10cc9ad: MOVQ 0x78(SP), CX
. . 10cc9b2: MOVQ CX, 0(SP)
. . 10cc9b6: CALL runtime.convT64(SB)
. . 10cc9bb: MOVQ 0x8(SP), AX
. . 10cc9c0: MOVQ AX, 0x1f8(SP)
. . 10cc9c8: MOVQ 0x70(SP), CX
. . 10cc9cd: MOVQ CX, 0(SP)
. . 10cc9d1: CALL runtime.convT64(SB)
. . 10cc9d6: MOVQ 0x8(SP), AX
. . 10cc9db: XORPS X0, X0
. . 10cc9de: MOVUPS X0, 0x2c0(SP)
. . 10cc9e6: MOVUPS X0, 0x2d0(SP)
. . 10cc9ee: LEAQ runtime.types+85760(SB), CX
. . 10cc9f5: MOVQ CX, 0x2c0(SP)
. . 10cc9fd: MOVQ 0x1f8(SP), DX
. . 10cca05: MOVQ DX, 0x2c8(SP)
. . 10cca0d: MOVQ CX, 0x2d0(SP)
. . 10cca15: MOVQ AX, 0x2d8(SP)
. . 10cca1d: MOVQ os.Stdout(SB), AX ;print.go:213
. . 10cca24: LEAQ go.itab.*os.File,io.Writer(SB), CX
. . 10cca2b: MOVQ CX, 0(SP)
. . 10cca2f: MOVQ AX, 0x8(SP)
. . 10cca34: LEAQ go.string.*+10897(SB), AX
. . 10cca3b: MOVQ AX, 0x10(SP)
. . 10cca40: MOVQ $0x14, 0x18(SP)
. . 10cca49: LEAQ 0x2c0(SP), AX
. . 10cca51: MOVQ AX, 0x20(SP)
. . 10cca56: MOVQ $0x2, 0x28(SP)
. . 10cca5f: MOVQ $0x2, 0x30(SP)
. . 10cca68: CALL fmt.Fprintf(SB)
. . 10cca6d: MOVQ main.dictStats(SB), AX ;main.go:55
. . 10cca74: CMPB $0x0, 0(AX)
. . 10cca77: JNE 0x10cd211
. . 10cca7d: MOVQ main.src(SB), AX ;main.go:59
. . 10cca84: MOVQ 0(AX), CX
. . 10cca87: MOVQ 0x8(AX), AX
. . 10cca8b: TESTQ AX, AX
. . 10cca8e: JE 0x10ccaa2
. . 10cca90: MOVQ main.dest(SB), DX
. . 10cca97: CMPQ $0x0, 0x8(DX)
. . 10cca9c: JNE 0x10cccae
. . 10ccaa2: MOVQ main.printGraph(SB), AX ;main.go:83
. . 10ccaa9: CMPB $0x0, 0(AX)
. . 10ccaac: JNE 0x10ccc98
. . 10ccab2: MOVQ main.memprofile(SB), AX ;main.go:87
. . 10ccab9: CMPQ $0x0, 0x8(AX)
. . 10ccabe: JNE 0x10ccad6
. . 10ccac0: NOPL ;main.go:98
. . 10ccac1: CALL runtime.deferreturn(SB)
. . 10ccac6: MOVQ 0x2e0(SP), BP
. . 10ccace: ADDQ $0x2e8, SP
. . 10ccad5: RET
. . 10ccad6: CALL runtime.GC(SB) ;main.go:88
. . 10ccadb: MOVQ main.memprofile(SB), AX ;main.go:89
. . 10ccae2: MOVQ 0(AX), CX
. . 10ccae5: MOVQ 0x8(AX), AX
. . 10ccae9: MOVQ CX, 0(SP) ;file.go:289
. . 10ccaed: MOVQ AX, 0x8(SP)
. . 10ccaf2: MOVQ $0x602, 0x10(SP)
. . 10ccafb: MOVL $0x1b6, 0x18(SP)
. . 10ccb03: CALL os.OpenFile(SB)
. . 10ccb08: MOVQ 0x20(SP), AX
. . 10ccb0d: MOVQ AX, 0x1f0(SP)
. . 10ccb15: MOVQ 0x28(SP), CX
. . 10ccb1a: MOVQ 0x30(SP), DX
. . 10ccb1f: TESTQ CX, CX ;main.go:90
. . 10ccb22: JE 0x10ccb8e
. . 10ccb24: JE 0x10ccb2a ;main.go:91
. . 10ccb26: MOVQ 0x8(CX), CX
. . 10ccb2a: XORPS X0, X0
. . 10ccb2d: MOVUPS X0, 0x260(SP)
. . 10ccb35: MOVUPS X0, 0x270(SP)
. . 10ccb3d: LEAQ runtime.types+88448(SB), AX
. . 10ccb44: MOVQ AX, 0x260(SP)
. . 10ccb4c: LEAQ internal/bytealg.IndexString.args_stackmap+672(SB), BX
. . 10ccb53: MOVQ BX, 0x268(SP)
. . 10ccb5b: MOVQ CX, 0x270(SP)
. . 10ccb63: MOVQ DX, 0x278(SP)
. . 10ccb6b: LEAQ 0x260(SP), CX
. . 10ccb73: MOVQ CX, 0(SP)
. . 10ccb77: MOVQ $0x2, 0x8(SP)
. . 10ccb80: MOVQ $0x2, 0x10(SP)
. . 10ccb89: CALL log.Fatal(SB)
. . 10ccb8e: MOVL $0x18, 0xf0(SP) ;main.go:93
. . 10ccb99: LEAQ go.func.*+293(SB), AX
. . 10ccba0: MOVQ AX, 0x108(SP)
. . 10ccba8: MOVQ 0x1f0(SP), AX
. . 10ccbb0: MOVQ AX, 0x120(SP)
. . 10ccbb8: LEAQ 0xf0(SP), CX
. . 10ccbc0: MOVQ CX, 0(SP)
. . 10ccbc4: CALL runtime.deferprocStack(SB)
. . 10ccbc9: TESTL AX, AX
. . 10ccbcb: JNE 0x10ccc82
. . 10ccbd1: NOPL ;pprof.go:522
. . 10ccbd2: LEAQ go.itab.*os.File,io.Writer(SB), AX ;pprof.go:533
. . 10ccbd9: MOVQ AX, 0(SP)
. . 10ccbdd: MOVQ 0x1f0(SP), AX
. . 10ccbe5: MOVQ AX, 0x8(SP)
. . 10ccbea: MOVQ $0x0, 0x10(SP)
. . 10ccbf3: XORPS X0, X0
. . 10ccbf6: MOVUPS X0, 0x18(SP)
. . 10ccbfb: CALL runtime/pprof.writeHeapInternal(SB)
. . 10ccc00: MOVQ 0x28(SP), AX
. . 10ccc05: MOVQ 0x30(SP), CX
. . 10ccc0a: TESTQ AX, AX ;main.go:94
. . 10ccc0d: JE 0x10ccac0
. . 10ccc13: JE 0x10ccc19 ;main.go:95
. . 10ccc15: MOVQ 0x8(AX), AX
. . 10ccc19: XORPS X0, X0
. . 10ccc1c: MOVUPS X0, 0x260(SP)
. . 10ccc24: MOVUPS X0, 0x270(SP)
. . 10ccc2c: LEAQ runtime.types+88448(SB), DX
. . 10ccc33: MOVQ DX, 0x260(SP)
. . 10ccc3b: LEAQ internal/bytealg.IndexString.args_stackmap+688(SB), DX
. . 10ccc42: MOVQ DX, 0x268(SP)
. . 10ccc4a: MOVQ AX, 0x270(SP)
. . 10ccc52: MOVQ CX, 0x278(SP)
. . 10ccc5a: LEAQ 0x260(SP), AX
. . 10ccc62: MOVQ AX, 0(SP)
. . 10ccc66: MOVQ $0x2, 0x8(SP)
. . 10ccc6f: MOVQ $0x2, 0x10(SP)
. . 10ccc78: CALL log.Fatal(SB)
. . 10ccc7d: JMP 0x10ccac0
. . 10ccc82: NOPL ;main.go:93
. . 10ccc83: CALL runtime.deferreturn(SB)
. . 10ccc88: MOVQ 0x2e0(SP), BP
. . 10ccc90: ADDQ $0x2e8, SP
. . 10ccc97: RET
. . 10ccc98: MOVQ 0x1d0(SP), AX ;main.go:84
. . 10ccca0: MOVQ AX, 0(SP)
. . 10ccca4: CALL main.(*Graph).PrintAdjList(SB)
. . 10ccca9: JMP 0x10ccab2
. . 10cccae: MOVQ CX, 0(SP) ;main.go:60
. . 10cccb2: MOVQ AX, 0x8(SP)
. . 10cccb7: CALL runtime.convTstring(SB)
. . 10cccbc: MOVQ main.dest(SB), AX
. . 10cccc3: MOVQ 0x10(SP), CX
. . 10cccc8: MOVQ CX, 0x1f8(SP)
. . 10cccd0: MOVQ 0(AX), DX
. . 10cccd3: MOVQ 0x8(AX), AX
. . 10cccd7: MOVQ DX, 0(SP)
. . 10cccdb: MOVQ AX, 0x8(SP)
. . 10ccce0: CALL runtime.convTstring(SB)
. . 10ccce5: MOVQ 0x10(SP), AX
. . 10cccea: XORPS X0, X0
. . 10ccced: MOVUPS X0, 0x2a0(SP)
. . 10cccf5: MOVUPS X0, 0x2b0(SP)
. . 10cccfd: LEAQ runtime.types+88448(SB), CX
. . 10ccd04: MOVQ CX, 0x2a0(SP)
. . 10ccd0c: MOVQ 0x1f8(SP), DX
. . 10ccd14: MOVQ DX, 0x2a8(SP)
. . 10ccd1c: MOVQ CX, 0x2b0(SP)
. . 10ccd24: MOVQ AX, 0x2b8(SP)
. . 10ccd2c: MOVQ os.Stdout(SB), AX ;print.go:213
. . 10ccd33: LEAQ go.itab.*os.File,io.Writer(SB), DX
. . 10ccd3a: MOVQ DX, 0(SP)
. . 10ccd3e: MOVQ AX, 0x8(SP)
. . 10ccd43: LEAQ go.string.*+16166(SB), AX
. . 10ccd4a: MOVQ AX, 0x10(SP)
. . 10ccd4f: MOVQ $0x1b, 0x18(SP)
. . 10ccd58: LEAQ 0x2a0(SP), AX
. . 10ccd60: MOVQ AX, 0x20(SP)
. . 10ccd65: MOVQ $0x2, 0x28(SP)
. . 10ccd6e: MOVQ $0x2, 0x30(SP)
. . 10ccd77: CALL fmt.Fprintf(SB)
. . 10ccd7c: MOVQ main.src(SB), AX ;main.go:61
. . 10ccd83: MOVQ 0x8(AX), CX
. . 10ccd87: MOVQ 0(AX), AX
. . 10ccd8a: MOVQ 0x1d0(SP), DX
. . 10ccd92: MOVQ DX, 0(SP)
. . 10ccd96: MOVQ AX, 0x8(SP)
. . 10ccd9b: MOVQ CX, 0x10(SP)
. . 10ccda0: CALL main.(*Graph).Find(SB)
. . 10ccda5: MOVQ main.dest(SB), AX ;main.go:62
. . 10ccdac: MOVQ 0x18(SP), CX ;main.go:61
. . 10ccdb1: MOVQ CX, 0x58(SP)
. . 10ccdb6: MOVQ 0x8(AX), DX ;main.go:62
. . 10ccdba: MOVQ 0(AX), AX
. . 10ccdbd: MOVQ 0x1d0(SP), BX
. . 10ccdc5: MOVQ BX, 0(SP)
. . 10ccdc9: MOVQ AX, 0x8(SP)
. . 10ccdce: MOVQ DX, 0x10(SP)
. . 10ccdd3: CALL main.(*Graph).Find(SB)
. . 10ccdd8: MOVQ 0x18(SP), AX
. . 10ccddd: MOVQ 0x58(SP), CX ;main.go:64
. . 10ccde2: TESTQ CX, CX
. . 10ccde5: JL 0x10cd0b6
. . 10ccdeb: TESTQ AX, AX
. . 10ccdee: JL 0x10cd0b3
. . 10ccdf4: XORPS X0, X0 ;main.go:74
. . 10ccdf7: MOVUPS X0, 0x220(SP)
. . 10ccdff: LEAQ runtime.types+88448(SB), AX
. . 10cce06: MOVQ AX, 0x220(SP)
. . 10cce0e: LEAQ internal/bytealg.IndexString.args_stackmap+656(SB), CX
. . 10cce15: MOVQ CX, 0x228(SP)
. . 10cce1d: MOVQ os.Stdout(SB), CX ;print.go:274
. . 10cce24: LEAQ go.itab.*os.File,io.Writer(SB), DX
. . 10cce2b: MOVQ DX, 0(SP)
. . 10cce2f: MOVQ CX, 0x8(SP)
. . 10cce34: LEAQ 0x220(SP), CX
. . 10cce3c: MOVQ CX, 0x10(SP)
. . 10cce41: MOVQ $0x1, 0x18(SP)
. . 10cce4a: MOVQ $0x1, 0x20(SP)
. . 10cce53: CALL fmt.Fprintln(SB)
. . 10cce58: MOVQ 0x1d0(SP), AX ;main.go:75
. . 10cce60: MOVQ AX, 0(SP)
. . 10cce64: MOVQ 0x58(SP), CX
. . 10cce69: MOVQ CX, 0x8(SP)
. . 10cce6e: CALL main.(*Graph).AllPaths(SB)
. . 10cce73: MOVQ main.dest(SB), AX ;main.go:76
. . 10cce7a: MOVQ 0x10(SP), CX ;main.go:75
. . 10cce7f: MOVQ 0x8(AX), DX ;main.go:76
. . 10cce83: MOVQ 0(AX), AX
. . 10cce86: MOVQ CX, 0(SP)
. . 10cce8a: MOVQ AX, 0x8(SP)
. . 10cce8f: MOVQ DX, 0x10(SP)
. . 10cce94: CALL main.(*Paths).To(SB)
. . 10cce99: MOVQ 0x18(SP), AX
. . 10cce9e: MOVQ AX, 0x1c8(SP)
. . 10ccea6: MOVQ 0x20(SP), CX
. . 10cceab: MOVQ CX, 0x60(SP)
. . 10cceb0: TESTQ CX, CX ;main.go:77
. . 10cceb3: JE 0x10ccfc5
. . 10cceb9: MOVQ 0x1d0(SP), DX ;main.go:80
. . 10ccec1: XORL BX, BX
. . 10ccec3: JMP 0x10ccfa3
. . 10ccec8: MOVQ BX, 0x78(SP)
. . 10ccecd: LEAQ 0(SI)(SI*2), AX ;main.go:81
. . 10cced1: MOVQ 0x10(R8)(AX*8), CX
. . 10cced6: MOVQ 0(R8)(AX*8), DX
. . 10cceda: MOVQ 0x8(R8)(AX*8), AX
. . 10ccedf: MOVQ $0x0, 0(SP)
. . 10ccee7: MOVQ DX, 0x8(SP)
. . 10cceec: MOVQ AX, 0x10(SP)
. . 10ccef1: MOVQ CX, 0x18(SP)
. . 10ccef6: CALL runtime.slicebytetostring(SB)
. . 10ccefb: MOVQ 0x28(SP), AX
. . 10ccf00: MOVQ 0x20(SP), CX
. . 10ccf05: MOVQ CX, 0(SP)
. . 10ccf09: MOVQ AX, 0x8(SP)
. . 10ccf0e: CALL runtime.convTstring(SB)
. . 10ccf13: MOVQ 0x10(SP), AX
. . 10ccf18: XORPS X0, X0
. . 10ccf1b: MOVUPS X0, 0x210(SP)
. . 10ccf23: LEAQ runtime.types+88448(SB), CX
. . 10ccf2a: MOVQ CX, 0x210(SP)
. . 10ccf32: MOVQ AX, 0x218(SP)
. . 10ccf3a: MOVQ os.Stdout(SB), AX ;print.go:274
. . 10ccf41: LEAQ go.itab.*os.File,io.Writer(SB), DX
. . 10ccf48: MOVQ DX, 0(SP)
. . 10ccf4c: MOVQ AX, 0x8(SP)
. . 10ccf51: LEAQ 0x210(SP), AX
. . 10ccf59: MOVQ AX, 0x10(SP)
. . 10ccf5e: MOVQ $0x1, 0x18(SP)
. . 10ccf67: MOVQ $0x1, 0x20(SP)
. . 10ccf70: CALL fmt.Fprintln(SB)
. . 10ccf75: MOVQ 0x78(SP), AX ;main.go:80
. . 10ccf7a: LEAQ 0x1(AX), BX
. . 10ccf7e: MOVQ 0x60(SP), AX
. . 10ccf83: MOVQ 0x1d0(SP), CX
. . 10ccf8b: MOVQ 0x1c8(SP), DX
. . 10ccf93: MOVQ DX, AX
. . 10ccf96: MOVQ 0x60(SP), CX
. . 10ccf9b: MOVQ 0x1d0(SP), DX ;main.go:81
. . 10ccfa3: CMPQ CX, BX ;main.go:80
. . 10ccfa6: JGE 0x10ccab2
. . 10ccfac: MOVQ 0(AX)(BX*8), SI
. . 10ccfb0: MOVQ 0x8(DX), DI ;main.go:81
. . 10ccfb4: MOVQ 0(DX), R8
. . 10ccfb7: CMPQ DI, SI
. . 10ccfba: JB 0x10ccec8
. . 10ccfc0: JMP 0x10cd4f9
. . 10ccfc5: MOVQ main.src(SB), AX ;main.go:78
. . 10ccfcc: MOVQ 0x8(AX), CX
. . 10ccfd0: MOVQ 0(AX), AX
. . 10ccfd3: MOVQ AX, 0(SP)
. . 10ccfd7: MOVQ CX, 0x8(SP)
. . 10ccfdc: CALL runtime.convTstring(SB)
. . 10ccfe1: MOVQ main.dest(SB), AX
. . 10ccfe8: MOVQ 0x10(SP), CX
. . 10ccfed: MOVQ CX, 0x1f8(SP)
. . 10ccff5: MOVQ 0x8(AX), DX
. . 10ccff9: MOVQ 0(AX), AX
. . 10ccffc: MOVQ AX, 0(SP)
. . 10cd000: MOVQ DX, 0x8(SP)
. . 10cd005: CALL runtime.convTstring(SB)
. . 10cd00a: MOVQ 0x10(SP), AX
. . 10cd00f: XORPS X0, X0
. . 10cd012: MOVUPS X0, 0x280(SP)
. . 10cd01a: MOVUPS X0, 0x290(SP)
. . 10cd022: LEAQ runtime.types+88448(SB), CX
. . 10cd029: MOVQ CX, 0x280(SP)
. . 10cd031: MOVQ 0x1f8(SP), DX
. . 10cd039: MOVQ DX, 0x288(SP)
. . 10cd041: MOVQ CX, 0x290(SP)
. . 10cd049: MOVQ AX, 0x298(SP)
. . 10cd051: MOVQ os.Stdout(SB), AX ;print.go:213
. . 10cd058: LEAQ go.itab.*os.File,io.Writer(SB), DX
. . 10cd05f: MOVQ DX, 0(SP)
. . 10cd063: MOVQ AX, 0x8(SP)
. . 10cd068: LEAQ go.string.*+19932(SB), AX
. . 10cd06f: MOVQ AX, 0x10(SP)
. . 10cd074: MOVQ $0x1f, 0x18(SP)
. . 10cd07d: LEAQ 0x280(SP), AX
. . 10cd085: MOVQ AX, 0x20(SP)
. . 10cd08a: MOVQ $0x2, 0x28(SP)
. . 10cd093: MOVQ $0x2, 0x30(SP)
. . 10cd09c: CALL fmt.Fprintf(SB)
. . 10cd0a1: MOVQ 0x1c8(SP), AX ;main.go:80
. . 10cd0a9: MOVQ 0x60(SP), CX
. . 10cd0ae: JMP 0x10cceb9
. . 10cd0b3: TESTQ CX, CX ;main.go:64
. . 10cd0b6: JL 0x10cd16f ;main.go:65
. . 10cd0bc: TESTQ AX, AX ;main.go:68
. . 10cd0bf: JL 0x10cd0d7
. . 10cd0c1: NOPL ;main.go:71
. . 10cd0c2: CALL runtime.deferreturn(SB)
. . 10cd0c7: MOVQ 0x2e0(SP), BP
. . 10cd0cf: ADDQ $0x2e8, SP
. . 10cd0d6: RET
. . 10cd0d7: MOVQ main.dest(SB), AX ;main.go:69
. . 10cd0de: MOVQ 0(AX), CX
. . 10cd0e1: MOVQ 0x8(AX), AX
. . 10cd0e5: MOVQ CX, 0(SP)
. . 10cd0e9: MOVQ AX, 0x8(SP)
. . 10cd0ee: CALL runtime.convTstring(SB)
. . 10cd0f3: MOVQ 0x10(SP), AX
. . 10cd0f8: XORPS X0, X0
. . 10cd0fb: MOVUPS X0, 0x230(SP)
. . 10cd103: LEAQ runtime.types+88448(SB), CX
. . 10cd10a: MOVQ CX, 0x230(SP)
. . 10cd112: MOVQ AX, 0x238(SP)
. . 10cd11a: MOVQ os.Stdout(SB), AX ;print.go:213
. . 10cd121: LEAQ go.itab.*os.File,io.Writer(SB), CX
. . 10cd128: MOVQ CX, 0(SP)
. . 10cd12c: MOVQ AX, 0x8(SP)
. . 10cd131: LEAQ go.string.*+7812(SB), AX
. . 10cd138: MOVQ AX, 0x10(SP)
. . 10cd13d: MOVQ $0x11, 0x18(SP)
. . 10cd146: LEAQ 0x230(SP), AX
. . 10cd14e: MOVQ AX, 0x20(SP)
. . 10cd153: MOVQ $0x1, 0x28(SP)
. . 10cd15c: MOVQ $0x1, 0x30(SP)
. . 10cd165: CALL fmt.Fprintf(SB)
. . 10cd16a: JMP 0x10cd0c1 ;main.go:71
. . 10cd16f: MOVQ AX, 0x50(SP) ;main.go:62
. . 10cd174: MOVQ main.src(SB), AX ;main.go:66
. . 10cd17b: MOVQ 0x8(AX), CX
. . 10cd17f: MOVQ 0(AX), AX
. . 10cd182: MOVQ AX, 0(SP)
. . 10cd186: MOVQ CX, 0x8(SP)
. . 10cd18b: CALL runtime.convTstring(SB)
. . 10cd190: MOVQ 0x10(SP), AX
. . 10cd195: XORPS X0, X0
. . 10cd198: MOVUPS X0, 0x240(SP)
. . 10cd1a0: LEAQ runtime.types+88448(SB), CX
. . 10cd1a7: MOVQ CX, 0x240(SP)
. . 10cd1af: MOVQ AX, 0x248(SP)
. . 10cd1b7: MOVQ os.Stdout(SB), AX ;print.go:213
. . 10cd1be: LEAQ go.itab.*os.File,io.Writer(SB), DX
. . 10cd1c5: MOVQ DX, 0(SP)
. . 10cd1c9: MOVQ AX, 0x8(SP)
. . 10cd1ce: LEAQ go.string.*+7812(SB), AX
. . 10cd1d5: MOVQ AX, 0x10(SP)
. . 10cd1da: MOVQ $0x11, 0x18(SP)
. . 10cd1e3: LEAQ 0x240(SP), BX
. . 10cd1eb: MOVQ BX, 0x20(SP)
. . 10cd1f0: MOVQ $0x1, 0x28(SP)
. . 10cd1f9: MOVQ $0x1, 0x30(SP)
. . 10cd202: CALL fmt.Fprintf(SB)
. . 10cd207: MOVQ 0x50(SP), AX ;main.go:68
. . 10cd20c: JMP 0x10cd0bc
. . 10cd211: MOVQ main.dict(SB), AX ;main.go:56
. . 10cd218: MOVQ 0x8(AX), CX
. . 10cd21c: MOVQ 0(AX), AX
. . 10cd21f: MOVQ AX, 0(SP)
. . 10cd223: MOVQ CX, 0x8(SP)
. . 10cd228: CALL main.dictionaryStats(SB)
. . 10cd22d: JMP 0x10cca7d
. . 10cd232: MOVQ AX, 0(SP) ;main.go:48
. . 10cd236: MOVQ CX, 0x8(SP)
. . 10cd23b: CALL main.createPathIfNotExists(SB)
. . 10cd240: JMP 0x10cc8de
. . 10cd245: NOPL ;main.go:38
. . 10cd246: MOVQ CX, 0(SP) ;file.go:289
. . 10cd24a: MOVQ AX, 0x8(SP)
. . 10cd24f: MOVQ $0x602, 0x10(SP)
. . 10cd258: MOVL $0x1b6, 0x18(SP)
. . 10cd260: CALL os.OpenFile(SB)
. . 10cd265: MOVQ 0x20(SP), AX
. . 10cd26a: MOVQ AX, 0x1d8(SP)
. . 10cd272: MOVQ 0x30(SP), CX
. . 10cd277: MOVQ 0x28(SP), DX
. . 10cd27c: TESTQ DX, DX ;main.go:39
. . 10cd27f: JE 0x10cd2eb
. . 10cd281: JE 0x10cd287 ;main.go:40
. . 10cd283: MOVQ 0x8(DX), DX
. . 10cd287: XORPS X0, X0
. . 10cd28a: MOVUPS X0, 0x260(SP)
. . 10cd292: MOVUPS X0, 0x270(SP)
. . 10cd29a: LEAQ runtime.types+88448(SB), AX
. . 10cd2a1: MOVQ AX, 0x260(SP)
. . 10cd2a9: LEAQ internal/bytealg.IndexString.args_stackmap+624(SB), BX
. . 10cd2b0: MOVQ BX, 0x268(SP)
. . 10cd2b8: MOVQ DX, 0x270(SP)
. . 10cd2c0: MOVQ CX, 0x278(SP)
. . 10cd2c8: LEAQ 0x260(SP), CX
. . 10cd2d0: MOVQ CX, 0(SP)
. . 10cd2d4: MOVQ $0x2, 0x8(SP)
. . 10cd2dd: MOVQ $0x2, 0x10(SP)
. . 10cd2e6: CALL log.Fatal(SB)
. . 10cd2eb: MOVL $0x18, 0x138(SP) ;main.go:42
. . 10cd2f6: LEAQ go.func.*+293(SB), AX
. . 10cd2fd: MOVQ AX, 0x150(SP)
. . 10cd305: MOVQ 0x1d8(SP), CX
. . 10cd30d: MOVQ CX, 0x168(SP)
. . 10cd315: LEAQ 0x138(SP), DX
. . 10cd31d: MOVQ DX, 0(SP)
. . 10cd321: CALL runtime.deferprocStack(SB)
. . 10cd326: TESTL AX, AX
. . 10cd328: JNE 0x10cd391
. . 10cd32a: LEAQ go.itab.*os.File,io.Writer(SB), AX ;main.go:43
. . 10cd331: MOVQ AX, 0(SP)
. . 10cd335: MOVQ 0x1d8(SP), CX
. . 10cd33d: MOVQ CX, 0x8(SP)
. . 10cd342: CALL runtime/trace.Start(SB)
. . 10cd347: MOVL $0x0, 0x80(SP) ;main.go:44
. . 10cd352: LEAQ go.func.*+1597(SB), AX
. . 10cd359: MOVQ AX, 0x98(SP)
. . 10cd361: LEAQ 0x80(SP), AX
. . 10cd369: MOVQ AX, 0(SP)
. . 10cd36d: CALL runtime.deferprocStack(SB)
. . 10cd372: TESTL AX, AX
. . 10cd374: JNE 0x10cd37b
. . 10cd376: JMP 0x10cc8c7
. . 10cd37b: NOPL
. . 10cd37c: CALL runtime.deferreturn(SB)
. . 10cd381: MOVQ 0x2e0(SP), BP
. . 10cd389: ADDQ $0x2e8, SP
. . 10cd390: RET
. . 10cd391: NOPL ;main.go:42
. . 10cd392: CALL runtime.deferreturn(SB)
. . 10cd397: MOVQ 0x2e0(SP), BP
. . 10cd39f: ADDQ $0x2e8, SP
. . 10cd3a6: RET
. . 10cd3a7: NOPL ;main.go:28
. . 10cd3a8: MOVQ CX, 0(SP) ;file.go:289
. . 10cd3ac: MOVQ AX, 0x8(SP)
. . 10cd3b1: MOVQ $0x602, 0x10(SP)
. . 10cd3ba: MOVL $0x1b6, 0x18(SP)
. . 10cd3c2: CALL os.OpenFile(SB)
. . 10cd3c7: MOVQ 0x20(SP), AX
. . 10cd3cc: MOVQ AX, 0x1e0(SP)
. . 10cd3d4: MOVQ 0x28(SP), CX
. . 10cd3d9: MOVQ CX, 0x68(SP)
. . 10cd3de: MOVQ 0x30(SP), DX
. . 10cd3e3: MOVQ DX, 0x1e8(SP)
. . 10cd3eb: MOVL $0x18, 0x180(SP) ;main.go:29
. . 10cd3f6: LEAQ go.func.*+293(SB), BX
. . 10cd3fd: MOVQ BX, 0x198(SP)
. . 10cd405: MOVQ AX, 0x1b0(SP)
. . 10cd40d: LEAQ 0x180(SP), SI
. . 10cd415: MOVQ SI, 0(SP)
. . 10cd419: CALL runtime.deferprocStack(SB)
. . 10cd41e: TESTL AX, AX
. . 10cd420: JNE 0x10cd4e3
. . 10cd426: MOVQ 0x68(SP), AX ;main.go:30
. . 10cd42b: TESTQ AX, AX
. . 10cd42e: JE 0x10cd47c
. . 10cd430: JE 0x10cd436 ;main.go:31
. . 10cd432: MOVQ 0x8(AX), AX
. . 10cd436: XORPS X0, X0
. . 10cd439: MOVUPS X0, 0x200(SP)
. . 10cd441: MOVQ AX, 0x200(SP)
. . 10cd449: MOVQ 0x1e8(SP), AX
. . 10cd451: MOVQ AX, 0x208(SP)
. . 10cd459: LEAQ 0x200(SP), AX
. . 10cd461: MOVQ AX, 0(SP)
. . 10cd465: MOVQ $0x1, 0x8(SP)
. . 10cd46e: MOVQ $0x1, 0x10(SP)
. . 10cd477: CALL log.Fatal(SB)
. . 10cd47c: LEAQ go.itab.*os.File,io.Writer(SB), AX ;main.go:33
. . 10cd483: MOVQ AX, 0(SP)
. . 10cd487: MOVQ 0x1e0(SP), CX
. . 10cd48f: MOVQ CX, 0x8(SP)
. . 10cd494: CALL runtime/pprof.StartCPUProfile(SB)
. . 10cd499: MOVL $0x0, 0xb8(SP) ;main.go:34
. . 10cd4a4: LEAQ go.func.*+1565(SB), AX
. . 10cd4ab: MOVQ AX, 0xd0(SP)
. . 10cd4b3: LEAQ 0xb8(SP), AX
. . 10cd4bb: MOVQ AX, 0(SP)
. . 10cd4bf: CALL runtime.deferprocStack(SB)
. . 10cd4c4: TESTL AX, AX
. . 10cd4c6: JNE 0x10cd4cd
. . 10cd4c8: JMP 0x10cc8b0
. . 10cd4cd: NOPL
. . 10cd4ce: CALL runtime.deferreturn(SB)
. . 10cd4d3: MOVQ 0x2e0(SP), BP
. . 10cd4db: ADDQ $0x2e8, SP
. . 10cd4e2: RET
. . 10cd4e3: NOPL ;main.go:29
. . 10cd4e4: CALL runtime.deferreturn(SB)
. . 10cd4e9: MOVQ 0x2e0(SP), BP
. . 10cd4f1: ADDQ $0x2e8, SP
. . 10cd4f8: RET
. . 10cd4f9: MOVQ SI, AX ;main.go:81
. . 10cd4fc: MOVQ DI, CX
. . 10cd4ff: CALL runtime.panicIndex(SB)
. . 10cd504: MOVL $0x1, AX ;flag.go:996
. . 10cd509: CALL runtime.panicSliceB(SB)
. . 10cd50e: NOPL
. . 10cd50f: CALL runtime.morestack_noctxt(SB) ;main.go:24
. . 10cd514: JMP main.main(SB)
. . 10cd519: INT $0x3
. . 10cd51a: INT $0x3
. . 10cd51b: INT $0x3
. . 10cd51c: INT $0x3
. . 10cd51d: INT $0x3
. . 10cd51e: INT $0x3
ROUTINE ======================== main.newIndex
90ms 120ms (flat, cum) 1.80% of Total
. . 10cbba0: MOVQ GS:0x30, CX ;index.go:16
. . 10cbba9: CMPQ 0x10(CX), SP
. . 10cbbad: JBE 0x10cbdae
. . 10cbbb3: SUBQ $0x48, SP
. . 10cbbb7: MOVQ BP, 0x40(SP)
. . 10cbbbc: LEAQ 0x40(SP), BP
. . 10cbbc1: LEAQ runtime.types+77120(SB), AX ;index.go:17
. . 10cbbc8: MOVQ AX, 0(SP)
. . 10cbbcc: MOVQ 0x50(SP), AX
. . 10cbbd1: MOVQ AX, 0x8(SP)
. . 10cbbd6: MOVQ AX, 0x10(SP)
. 20ms 10cbbdb: CALL runtime.makeslice(SB) ;main.newIndex index.go:17
. . 10cbbe0: MOVQ 0x18(SP), AX ;index.go:17
. . 10cbbe5: MOVQ AX, 0x38(SP)
. . 10cbbea: XORL CX, CX
. . 10cbbec: JMP 0x10cbbf5 ;index.go:18
. . 10cbbee: LEAQ 0x1(AX), CX
. . 10cbbf2: MOVQ BX, AX ;index.go:19
. . 10cbbf5: MOVQ 0x50(SP), DX ;index.go:18
. . 10cbbfa: CMPQ DX, CX
. . 10cbbfd: JGE 0x10cbc64
. . 10cbbff: MOVQ CX, 0x20(SP)
. . 10cbc04: LEAQ runtime.types+85760(SB), AX ;index.go:19
. . 10cbc0b: MOVQ AX, 0(SP)
. . 10cbc0f: XORPS X0, X0
. . 10cbc12: MOVUPS X0, 0x8(SP)
10ms 10ms 10cbc17: CALL runtime.makeslice(SB) ;main.newIndex index.go:19
. . 10cbc1c: MOVQ 0x20(SP), AX ;index.go:19
. . 10cbc21: LEAQ 0(AX)(AX*2), CX
. . 10cbc25: MOVQ 0x18(SP), DX
10ms 10ms 10cbc2a: MOVQ 0x38(SP), BX ;main.newIndex index.go:19
20ms 20ms 10cbc2f: MOVQ $0x0, 0x8(BX)(CX*8)
30ms 30ms 10cbc38: MOVQ $0x0, 0x10(BX)(CX*8)
. . 10cbc41: LEAQ 0(BX)(CX*8), DI ;index.go:19
. . 10cbc45: CMPL $0x0, runtime.writeBarrier(SB)
. . 10cbc4c: JNE 0x10cbc54
20ms 20ms 10cbc4e: MOVQ DX, 0(BX)(CX*8) ;main.newIndex index.go:19
. . 10cbc52: JMP 0x10cbbee ;index.go:19
. . 10cbc54: MOVQ AX, CX ;index.go:18
. . 10cbc57: MOVQ DX, AX ;index.go:19
. 10ms 10cbc5a: CALL runtime.gcWriteBarrier(SB) ;main.newIndex index.go:19
. . 10cbc5f: MOVQ CX, AX ;index.go:18
. . 10cbc62: JMP 0x10cbbee ;index.go:19
. . 10cbc64: NOPL ;murmur64.go:18
. . 10cbc65: MOVL $0x0, 0(SP) ;murmur64.go:22
. . 10cbc6c: CALL erichgess/wordladder/vendor/github.com/spaolacci/murmur3.New128WithSeed(SB)
. . 10cbc71: MOVQ 0x10(SP), AX
. . 10cbc76: MOVQ 0x8(SP), CX
. . 10cbc7b: LEAQ go.itab.*erichgess/wordladder/vendor/github.com/spaolacci/murmur3.digest128,erichgess/wordladder/vendor/github.com/spaolacci/murmur3.Hash128(SB), DX
. . 10cbc82: CMPQ DX, CX
. . 10cbc85: JNE 0x10cbd8c
. . 10cbc8b: MOVQ AX, 0x28(SP)
. . 10cbc90: LEAQ runtime.types+88768(SB), AX ;index.go:23
. . 10cbc97: MOVQ AX, 0(SP)
. . 10cbc9b: MOVQ $0x0, 0x8(SP)
. . 10cbca4: MOVQ 0x58(SP), AX
. . 10cbca9: MOVQ AX, 0x10(SP)
. . 10cbcae: CALL runtime.makeslice(SB)
. . 10cbcb3: MOVQ 0x18(SP), AX
. . 10cbcb8: MOVQ AX, 0x30(SP)
. . 10cbcbd: LEAQ runtime.types+195072(SB), CX ;index.go:25
. . 10cbcc4: MOVQ CX, 0(SP)
. . 10cbcc8: CALL runtime.newobject(SB)
. . 10cbccd: MOVQ 0x8(SP), AX
;index.go:22
. . 10cbcd2: LEAQ go.itab.*erichgess/wordladder/vendor/github.com/spaolacci/murmur3.digest64,hash.Hash64(SB), CX
. . 10cbcd9: MOVQ CX, 0(AX)
. . 10cbcdc: CMPL $0x0, runtime.writeBarrier(SB)
. . 10cbce3: JNE 0x10cbd73
. . 10cbce9: MOVQ 0x28(SP), CX
. . 10cbcee: MOVQ CX, 0x8(AX)
. . 10cbcf2: MOVQ $0x0, 0x30(AX) ;index.go:23
. . 10cbcfa: MOVQ 0x58(SP), CX
. . 10cbcff: MOVQ CX, 0x38(AX)
. . 10cbd03: CMPL $0x0, runtime.writeBarrier(SB)
. . 10cbd0a: JNE 0x10cbd5d
. . 10cbd0c: MOVQ 0x30(SP), CX
. . 10cbd11: MOVQ CX, 0x28(AX)
. . 10cbd15: MOVQ 0x50(SP), CX ;index.go:24
. . 10cbd1a: MOVQ CX, 0x18(AX)
. . 10cbd1e: MOVQ CX, 0x20(AX)
. . 10cbd22: CMPL $0x0, runtime.writeBarrier(SB)
. . 10cbd29: JNE 0x10cbd47
. . 10cbd2b: MOVQ 0x38(SP), DX
. . 10cbd30: MOVQ DX, 0x10(AX)
. . 10cbd34: MOVQ CX, 0x40(AX) ;index.go:25
. . 10cbd38: MOVQ AX, 0x60(SP) ;index.go:21
. . 10cbd3d: MOVQ 0x40(SP), BP
. . 10cbd42: ADDQ $0x48, SP
. . 10cbd46: RET
. . 10cbd47: LEAQ 0x10(AX), DI ;index.go:24
. . 10cbd4b: MOVQ AX, DX ;index.go:25
. . 10cbd4e: MOVQ 0x38(SP), AX ;index.go:24
. . 10cbd53: CALL runtime.gcWriteBarrier(SB)
. . 10cbd58: MOVQ DX, AX ;index.go:25
. . 10cbd5b: JMP 0x10cbd34 ;index.go:24
. . 10cbd5d: LEAQ 0x28(AX), DI ;index.go:23
. . 10cbd61: MOVQ AX, CX ;index.go:25
. . 10cbd64: MOVQ 0x30(SP), AX ;index.go:23
. . 10cbd69: CALL runtime.gcWriteBarrier(SB)
. . 10cbd6e: MOVQ CX, AX ;index.go:24
. . 10cbd71: JMP 0x10cbd15 ;index.go:23
. . 10cbd73: LEAQ 0x8(AX), DI ;index.go:22
. . 10cbd77: MOVQ AX, CX ;index.go:25
. . 10cbd7a: MOVQ 0x28(SP), AX ;index.go:22
. . 10cbd7f: CALL runtime.gcWriteBarrier(SB)
. . 10cbd84: MOVQ CX, AX ;index.go:23
. . 10cbd87: JMP 0x10cbcf2 ;index.go:22
. . 10cbd8c: MOVQ CX, 0(SP) ;murmur64.go:22
. . 10cbd90: LEAQ runtime.types+199968(SB), AX
. . 10cbd97: MOVQ AX, 0x8(SP)
. . 10cbd9c: LEAQ runtime.types+156064(SB), AX
. . 10cbda3: MOVQ AX, 0x10(SP)
. . 10cbda8: CALL runtime.panicdottypeI(SB)
. . 10cbdad: NOPL
. . 10cbdae: CALL runtime.morestack_noctxt(SB) ;index.go:16
. . 10cbdb3: JMP main.newIndex(SB)
. . 10cbdb8: INT $0x3
. . 10cbdb9: INT $0x3
. . 10cbdba: INT $0x3
. . 10cbdbb: INT $0x3
. . 10cbdbc: INT $0x3
. . 10cbdbd: INT $0x3
. . 10cbdbe: INT $0x3
ROUTINE ======================== runtime.main
0 3.32s (flat, cum) 49.85% of Total
. . 102caf0: MOVQ GS:0x30, CX ;proc.go:113
. . 102caf9: CMPQ 0x10(CX), SP
. . 102cafd: JBE 0x102ce70
. . 102cb03: SUBQ $0x78, SP
. . 102cb07: MOVQ BP, 0x70(SP)
. . 102cb0c: LEAQ 0x70(SP), BP
. . 102cb11: MOVQ GS:0x30, AX ;proc.go:114
. . 102cb1a: MOVQ AX, 0x68(SP)
. . 102cb1f: MOVQ 0x30(AX), CX ;proc.go:118
. . 102cb23: MOVQ 0(CX), CX
. . 102cb26: MOVQ $0x0, 0x130(CX)
;proc.go:124
. . 102cb31: MOVQ $0x3b9aca00, runtime.maxstacksize(SB)
. . 102cb3c: MOVB $0x1, runtime.mainStarted(SB) ;proc.go:130
. . 102cb43: LEAQ go.func.*+949(SB), CX ;proc.go:133
. . 102cb4a: MOVQ CX, 0(SP)
. . 102cb4e: CALL runtime.systemstack(SB)
. . 102cb53: MOVQ GS:0x30, AX ;proc.go:3550
. . 102cb5c: MOVQ 0x30(AX), AX
. . 102cb60: NOPL ;proc.go:144
. . 102cb61: INCL 0x274(AX) ;proc.go:3550
. . 102cb67: MOVQ GS:0x30, AX ;proc.go:3511
. . 102cb70: MOVQ 0x30(AX), CX ;proc.go:3512
. . 102cb74: NOPL ;proc.go:3551
. . 102cb75: MOVQ AX, DX ;runtime2.go:254
. . 102cb78: MOVQ AX, 0x168(CX)
. . 102cb7f: MOVQ 0x30(DX), AX ;proc.go:3513
. . 102cb83: MOVQ AX, 0xd8(DX) ;runtime2.go:292
. . 102cb8a: MOVQ 0x68(SP), AX ;proc.go:146
. . 102cb8f: MOVQ 0x30(AX), AX
. . 102cb93: LEAQ runtime.m0(SB), CX
. . 102cb9a: CMPQ CX, AX
. . 102cb9d: JNE 0x102ce56
. . 102cba3: LEAQ runtime..inittask(SB), AX ;proc.go:150
. . 102cbaa: MOVQ AX, 0(SP)
. . 102cbae: CALL runtime.doInit(SB)
. . 102cbb3: CALL runtime.nanotime(SB) ;proc.go:151
. . 102cbb8: CMPQ $0x0, 0(SP)
. . 102cbbd: JE 0x102ce3d
. . 102cbc3: MOVB $0x1, 0x27(SP) ;proc.go:156
. . 102cbc8: MOVL $0x8, 0x30(SP) ;proc.go:157
. . 102cbd0: LEAQ go.func.*+957(SB), AX
. . 102cbd7: MOVQ AX, 0x48(SP)
. . 102cbdc: LEAQ 0x27(SP), AX
. . 102cbe1: MOVQ AX, 0x60(SP)
. . 102cbe6: LEAQ 0x30(SP), AX
. . 102cbeb: MOVQ AX, 0(SP)
. . 102cbef: CALL runtime.deferprocStack(SB)
. . 102cbf4: TESTL AX, AX
. . 102cbf6: JNE 0x102cdc9
. . 102cbfc: CALL runtime.nanotime(SB) ;proc.go:164
. . 102cc01: MOVQ 0(SP), AX
. . 102cc05: MOVQ AX, runtime.runtimeInitTime(SB)
. . 102cc0c: CALL runtime.gcenable(SB) ;proc.go:166
. . 102cc11: LEAQ runtime.types+83008(SB), AX ;proc.go:168
. . 102cc18: MOVQ AX, 0(SP)
. . 102cc1c: MOVQ $0x0, 0x8(SP)
. . 102cc25: CALL runtime.makechan(SB)
. . 102cc2a: MOVQ 0x10(SP), AX
. . 102cc2f: CMPL $0x0, runtime.writeBarrier(SB)
. . 102cc36: JNE 0x102cdb8
. . 102cc3c: MOVQ AX, runtime.main_init_done(SB)
. . 102cc43: CMPB $0x0, runtime.iscgo(SB) ;proc.go:169
. . 102cc4a: JE 0x102ccba
. . 102cc4c: CMPQ $0x0, __cgo_thread_start(SB) ;proc.go:170
. . 102cc54: JE 0x102ce24
. . 102cc5a: CMPQ $0x0, runtime._cgo_setenv(SB) ;proc.go:174
. . 102cc62: JE 0x102ce0b
. . 102cc68: CMPQ $0x0, runtime._cgo_unsetenv(SB) ;proc.go:177
. . 102cc70: JE 0x102cdf2
;proc.go:181
. . 102cc76: CMPQ $0x0, __cgo_notify_runtime_init_done(SB)
. . 102cc7e: JE 0x102cdd9
. . 102cc84: XORL AX, AX ;proc.go:1865
. . 102cc86: LEAQ runtime.newmHandoff+32(SB), CX
. . 102cc8d: MOVL $0x1, DX
. . 102cc92: LOCK CMPXCHGL DX, 0(CX)
. . 102cc96: SETE CL
. . 102cc99: TESTL CL, CL
. . 102cc9b: JNE 0x102cd9a
;proc.go:187
. . 102cca1: MOVQ __cgo_notify_runtime_init_done(SB), AX
. . 102cca8: MOVQ AX, 0(SP)
. . 102ccac: MOVQ $0x0, 0x8(SP)
. . 102ccb5: CALL runtime.cgocall(SB)
. . 102ccba: LEAQ main..inittask(SB), AX ;proc.go:190
. . 102ccc1: MOVQ AX, 0(SP)
. . 102ccc5: CALL runtime.doInit(SB)
. . 102ccca: MOVQ runtime.main_init_done(SB), AX ;proc.go:192
. . 102ccd1: MOVQ AX, 0(SP)
. . 102ccd5: CALL runtime.closechan(SB)
. . 102ccda: MOVB $0x0, 0x27(SP) ;proc.go:194
. . 102ccdf: CALL runtime.unlockOSThread(SB) ;proc.go:195
. . 102cce4: CMPB $0x0, runtime.isarchive(SB) ;proc.go:197
. . 102cceb: JNE 0x102cd8a
. . 102ccf1: CMPB $0x0, runtime.islibrary(SB)
. . 102ccf8: JNE 0x102cd8a
. . 102ccfe: MOVQ go.func.*+965(SB), AX ;proc.go:203
. . 102cd05: LEAQ go.func.*+965(SB), DX
. 3.32s 102cd0c: CALL AX ;runtime.main proc.go:203
. . 102cd0e: MOVL runtime.runningPanicDefers(SB), AX ;proc.go:212
. . 102cd14: TESTL AX, AX
. . 102cd16: JE 0x102cd4c
. . 102cd18: XORL AX, AX
. . 102cd1a: JMP 0x102cd3a ;proc.go:214
. . 102cd1c: MOVQ AX, 0x28(SP)
. . 102cd21: NOPL ;proc.go:218
. . 102cd22: LEAQ go.func.*+893(SB), AX ;proc.go:269
. . 102cd29: MOVQ AX, 0(SP)
. . 102cd2d: CALL runtime.mcall(SB)
. . 102cd32: MOVQ 0x28(SP), AX ;proc.go:214
. . 102cd37: INCQ AX
. . 102cd3a: CMPQ $0x3e8, AX
. . 102cd40: JGE 0x102cd4c
. . 102cd42: MOVL runtime.runningPanicDefers(SB), CX ;proc.go:215
. . 102cd48: TESTL CX, CX
. . 102cd4a: JNE 0x102cd1c
. . 102cd4c: MOVL runtime.panicking(SB), AX ;proc.go:221
. . 102cd52: TESTL AX, AX
. . 102cd54: JNE 0x102cd6c
. . 102cd56: MOVL $0x0, 0(SP) ;proc.go:225
. . 102cd5d: CALL runtime.exit(SB)
. . 102cd62: XORL AX, AX ;proc.go:228
. . 102cd64: MOVL $0x0, 0(AX)
. . 102cd6a: JMP 0x102cd62
. . 102cd6c: XORPS X0, X0 ;proc.go:222
. . 102cd6f: MOVUPS X0, 0(SP)
. . 102cd73: MOVW $0x1008, 0x10(SP)
. . 102cd7a: MOVQ $0x1, 0x18(SP)
. . 102cd83: CALL runtime.gopark(SB)
. . 102cd88: JMP 0x102cd56
. . 102cd8a: NOPL ;proc.go:200
. . 102cd8b: CALL runtime.deferreturn(SB)
. . 102cd90: MOVQ 0x70(SP), BP
. . 102cd95: ADDQ $0x78, SP
. . 102cd99: RET
. . 102cd9a: LEAQ go.func.*+1509(SB), AX ;proc.go:1868
. . 102cda1: MOVQ AX, 0(SP)
. . 102cda5: MOVQ $0x0, 0x8(SP)
. . 102cdae: CALL runtime.newm(SB)
. . 102cdb3: JMP 0x102cca1 ;proc.go:186
. . 102cdb8: LEAQ runtime.main_init_done(SB), DI ;proc.go:168
. . 102cdbf: CALL runtime.gcWriteBarrier(SB)
. . 102cdc4: JMP 0x102cc43
. . 102cdc9: NOPL ;proc.go:157
. . 102cdca: CALL runtime.deferreturn(SB)
. . 102cdcf: MOVQ 0x70(SP), BP
. . 102cdd4: ADDQ $0x78, SP
. . 102cdd8: RET
. . 102cdd9: LEAQ go.string.*+25131(SB), AX ;proc.go:182
. . 102cde0: MOVQ AX, 0(SP)
. . 102cde4: MOVQ $0x25, 0x8(SP)
. . 102cded: CALL runtime.throw(SB)
. . 102cdf2: LEAQ go.string.*+11787(SB), AX ;proc.go:178
. . 102cdf9: MOVQ AX, 0(SP)
. . 102cdfd: MOVQ $0x15, 0x8(SP)
. . 102ce06: CALL runtime.throw(SB)
. . 102ce0b: LEAQ go.string.*+9742(SB), AX ;proc.go:175
. . 102ce12: MOVQ AX, 0(SP)
. . 102ce16: MOVQ $0x13, 0x8(SP)
. . 102ce1f: CALL runtime.throw(SB)
. . 102ce24: LEAQ go.string.*+14919(SB), AX ;proc.go:171
. . 102ce2b: MOVQ AX, 0(SP)
. . 102ce2f: MOVQ $0x19, 0x8(SP)
. . 102ce38: CALL runtime.throw(SB)
. . 102ce3d: LEAQ go.string.*+13763(SB), AX ;proc.go:152
. . 102ce44: MOVQ AX, 0(SP)
. . 102ce48: MOVQ $0x17, 0x8(SP)
. . 102ce51: CALL runtime.throw(SB)
. . 102ce56: LEAQ go.string.*+12882(SB), AX ;proc.go:147
. . 102ce5d: MOVQ AX, 0(SP)
. . 102ce61: MOVQ $0x16, 0x8(SP)
. . 102ce6a: CALL runtime.throw(SB)
. . 102ce6f: NOPL
. . 102ce70: CALL runtime.morestack_noctxt(SB) ;proc.go:113
. . 102ce75: JMP runtime.main(SB)
. . 102ce7a: INT $0x3
. . 102ce7b: INT $0x3
. . 102ce7c: INT $0x3
. . 102ce7d: INT $0x3
. . 102ce7e: INT $0x3
|
global _update
segment .data
blast db 255
segment .text
_update:
push ebx
push edi
push esi
push ebp
mov ebp,ecx
mov ebx,eax
mov ecx,784382
ulp:
xor eax,eax
mov eax,[ebx+ecx]
add eax,[ebx+ecx+1024]
add eax,[ebx+ecx+2048]
add ah,al
shr eax,8
add al,ah
cmp al,3
setz byte [edx+ecx+1025]
cmp al,4
setz al
and al,[ebx+ecx+1025]
or [edx+ecx+1025],al
mov al,[edx+ecx+1025]
mul byte [blast]
mov [ebp+ecx+1025],al
loop ulp
mov ecx,030000h
mov edi,ebx
mov esi,edx
cld
rep movsd
pop ebp
pop esi
pop edi
pop ebx
ret |
// File_Extractor 0.4.0. http://www.slack.net/~ant/
#define _CRT_SECURE_NO_WARNINGS
#include "Data_Reader.h"
#include "blargg_endian.h"
#include <assert.h>
#include <string.h>
#include <stdio.h>
/* Copyright (C) 2005-2006 Shay Green. This module is free software; you
can redistribute it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version. This
module is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details. You should have received a copy of the GNU Lesser General Public
License along with this module; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */
#include "blargg_source.h"
const char Data_Reader::eof_error [] = "Unexpected end of file";
blargg_err_t Data_Reader::read( void* p, long s )
{
long result = read_avail( p, s );
if ( result != s )
{
if ( result >= 0 && result < s )
return eof_error;
return "Read error";
}
return 0;
}
blargg_err_t Data_Reader::skip( long count )
{
char buf [512];
while ( count )
{
long n = sizeof buf;
if ( n > count )
n = count;
count -= n;
RETURN_ERR( read( buf, n ) );
}
return 0;
}
long File_Reader::remain() const { return size() - tell(); }
blargg_err_t File_Reader::skip( long n )
{
assert( n >= 0 );
if ( !n )
return 0;
return seek( tell() + n );
}
// Subset_Reader
Subset_Reader::Subset_Reader( Data_Reader* dr, long size )
{
in = dr;
remain_ = dr->remain();
if ( remain_ > size )
remain_ = size;
}
long Subset_Reader::remain() const { return remain_; }
long Subset_Reader::read_avail( void* p, long s )
{
if ( s > remain_ )
s = remain_;
remain_ -= s;
return in->read_avail( p, s );
}
// Remaining_Reader
Remaining_Reader::Remaining_Reader( void const* h, long size, Data_Reader* r )
{
header = (char const*) h;
header_end = header + size;
in = r;
}
long Remaining_Reader::remain() const { return long(header_end - header + in->remain()); }
long Remaining_Reader::read_first( void* out, long count )
{
long first = long(header_end - header);
if ( first )
{
if ( first > count )
first = count;
void const* old = header;
header += first;
memcpy( out, old, first );
}
return first;
}
long Remaining_Reader::read_avail( void* out, long count )
{
long first = read_first( out, count );
long second = count - first;
if ( second )
{
second = in->read_avail( (char*) out + first, second );
if ( second <= 0 )
return second;
}
return first + second;
}
blargg_err_t Remaining_Reader::read( void* out, long count )
{
long first = read_first( out, count );
long second = count - first;
if ( !second )
return 0;
return in->read( (char*) out + first, second );
}
// Mem_File_Reader
Mem_File_Reader::Mem_File_Reader( const void* p, long s ) :
begin( (const char*) p ),
size_( s )
{
pos = 0;
}
long Mem_File_Reader::size() const { return size_; }
long Mem_File_Reader::read_avail( void* p, long s )
{
long r = remain();
if ( s > r )
s = r;
memcpy( p, begin + pos, s );
pos += s;
return s;
}
long Mem_File_Reader::tell() const { return pos; }
blargg_err_t Mem_File_Reader::seek( long n )
{
if ( n > size_ )
return eof_error;
pos = n;
return 0;
}
// Callback_Reader
Callback_Reader::Callback_Reader( callback_t c, long size, void* d ) :
callback( c ),
data( d )
{
remain_ = size;
}
long Callback_Reader::remain() const { return remain_; }
long Callback_Reader::read_avail( void* out, long count )
{
if ( count > remain_ )
count = remain_;
if ( Callback_Reader::read( out, count ) )
count = -1;
return count;
}
blargg_err_t Callback_Reader::read( void* out, long count )
{
if ( count > remain_ )
return eof_error;
return callback( data, out, count );
}
// Std_File_Reader
Std_File_Reader::Std_File_Reader() : file_( 0 ) { }
Std_File_Reader::~Std_File_Reader() { close(); }
blargg_err_t Std_File_Reader::open( const char* path )
{
file_ = fopen( path, "rb" );
if ( !file_ )
return "Couldn't open file";
return 0;
}
long Std_File_Reader::size() const
{
long pos = tell();
fseek( (FILE*) file_, 0, SEEK_END );
long result = tell();
fseek( (FILE*) file_, pos, SEEK_SET );
return result;
}
long Std_File_Reader::read_avail( void* p, long s )
{
return (long)fread( p, 1, s, (FILE*) file_ );
}
blargg_err_t Std_File_Reader::read( void* p, long s )
{
if ( s == (long) fread( p, 1, s, (FILE*) file_ ) )
return 0;
if ( feof( (FILE*) file_ ) )
return eof_error;
return "Couldn't read from file";
}
long Std_File_Reader::tell() const { return ftell( (FILE*) file_ ); }
blargg_err_t Std_File_Reader::seek( long n )
{
if ( !fseek( (FILE*) file_, n, SEEK_SET ) )
return 0;
if ( n > size() )
return eof_error;
return "Error seeking in file";
}
void Std_File_Reader::close()
{
if ( file_ )
{
fclose( (FILE*) file_ );
file_ = 0;
}
}
// Gzip_File_Reader
#ifdef HAVE_ZLIB_H
#include "zlib.h"
static const char* get_gzip_eof( const char* path, long* eof )
{
FILE* file = fopen( path, "rb" );
if ( !file )
return "Couldn't open file";
unsigned char buf [4];
if ( fread( buf, 2, 1, file ) > 0 && buf [0] == 0x1F && buf [1] == 0x8B )
{
fseek( file, -4, SEEK_END );
fread( buf, 4, 1, file );
*eof = get_le32( buf );
}
else
{
fseek( file, 0, SEEK_END );
*eof = ftell( file );
}
const char* err = (ferror( file ) || feof( file )) ? "Couldn't get file size" : 0;
fclose( file );
return err;
}
Gzip_File_Reader::Gzip_File_Reader() : file_( 0 ) { }
Gzip_File_Reader::~Gzip_File_Reader() { close(); }
blargg_err_t Gzip_File_Reader::open( const char* path )
{
close();
RETURN_ERR( get_gzip_eof( path, &size_ ) );
file_ = gzopen( path, "rb" );
if ( !file_ )
return "Couldn't open file";
return 0;
}
long Gzip_File_Reader::size() const { return size_; }
long Gzip_File_Reader::read_avail( void* p, long s ) { return gzread( file_, p, s ); }
long Gzip_File_Reader::tell() const { return gztell( file_ ); }
blargg_err_t Gzip_File_Reader::seek( long n )
{
if ( gzseek( file_, n, SEEK_SET ) >= 0 )
return 0;
if ( n > size_ )
return eof_error;
return "Error seeking in file";
}
void Gzip_File_Reader::close()
{
if ( file_ )
{
gzclose( file_ );
file_ = 0;
}
}
#endif
|
dnl IA-64 mpn_and_n, mpn_andn_n, mpn_nand_n, mpn_ior_n, mpn_iorn_n,
dnl mpn_nior_n, mpn_xor_n, mpn_xnor_n -- mpn bitwise logical operations.
dnl Copyright 2003, 2004, 2005 Free Software Foundation, Inc.
dnl
dnl This file is part of the GNU MP Library.
dnl
dnl The GNU MP Library is free software; you can redistribute it and/or modify
dnl it under the terms of the GNU Lesser General Public License as published
dnl by the Free Software Foundation; either version 3 of the License, or (at
dnl your option) any later version.
dnl
dnl The GNU MP Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
dnl License for more details.
dnl
dnl You should have received a copy of the GNU Lesser General Public License
dnl along with the GNU MP Library. If not, see http://www.gnu.org/licenses/.
include(`../config.m4')
C cycles/limb
C Itanium: 2
C Itanium 2: 1
C TODO
C * Use rp,rpx scheme of aors_n.asm to allow parallel stores (useful in
C wind-down code).
C INPUT PARAMETERS
define(`rp', `r32')
define(`up', `r33')
define(`vp', `r34')
define(`n', `r35')
define(`OPERATION_xor_n',1)
ifdef(`OPERATION_and_n',
` define(`func',`mpn_and_n')
define(`logop', `and $1 = $2, $3')
define(`notormov', `mov $1 = $2')')
ifdef(`OPERATION_andn_n',
` define(`func',`mpn_andn_n')
define(`logop', `andcm $1 = $2, $3')
define(`notormov', `mov $1 = $2')')
ifdef(`OPERATION_nand_n',
` define(`func',`mpn_nand_n')
define(`logop', `and $1 = $2, $3')
define(`notormov', `sub $1 = -1, $2')')
ifdef(`OPERATION_ior_n',
` define(`func',`mpn_ior_n')
define(`logop', `or $1 = $2, $3')
define(`notormov', `mov $1 = $2')')
ifdef(`OPERATION_iorn_n',
` define(`func',`mpn_iorn_n')
define(`logop', `andcm $1 = $3, $2')
define(`notormov', `sub $1 = -1, $2')')
ifdef(`OPERATION_nior_n',
` define(`func',`mpn_nior_n')
define(`logop', `or $1 = $2, $3')
define(`notormov', `sub $1 = -1, $2')')
ifdef(`OPERATION_xor_n',
` define(`func',`mpn_xor_n')
define(`logop', `xor $1 = $2, $3')
define(`notormov', `mov $1 = $2')')
ifdef(`OPERATION_xnor_n',
` define(`func',`mpn_xnor_n')
define(`logop', `xor $1 = $2, $3')
define(`notormov', `sub $1 = -1, $2')')
ASM_START()
PROLOGUE(func)
.prologue
.save ar.lc, r2
.body
ifdef(`HAVE_ABI_32',
` addp4 rp = 0, rp C M I
addp4 up = 0, up C M I
addp4 vp = 0, vp C M I
zxt4 n = n C I
;;
')
{.mmi
ld8 r10 = [up], 8 C M
ld8 r11 = [vp], 8 C M
mov.i r2 = ar.lc C I0
}
{.mmi
and r14 = 3, n C M I
cmp.lt p15, p14 = 4, n C M I
shr.u n = n, 2 C I0
;;
}
{.mmi
cmp.eq p6, p0 = 1, r14 C M I
cmp.eq p7, p0 = 2, r14 C M I
cmp.eq p8, p0 = 3, r14 C M I
}
{.bbb
(p6) br.dptk .Lb01 C B
(p7) br.dptk .Lb10 C B
(p8) br.dptk .Lb11 C B
}
.Lb00: ld8 r17 = [up], 8 C M
ld8 r21 = [vp], 8 C M
add n = -2, n C M I
;;
ld8 r18 = [up], 8 C M
ld8 r22 = [vp], 8 C M
;;
ld8 r19 = [up], 8 C M
ld8 r23 = [vp], 8 C M
(p15) br.cond.dpnt .grt4 C B
logop( r14, r10, r11) C M I
;;
logop( r15, r17, r21) C M I
notormov( r8, r14) C M I
br .Lcj4 C B
.grt4: logop( r14, r10, r11) C M I
ld8 r16 = [up], 8 C M
ld8 r20 = [vp], 8 C M
;;
logop( r15, r17, r21) C M I
ld8 r17 = [up], 8 C M
mov.i ar.lc = n C I0
notormov( r8, r14) C M I
ld8 r21 = [vp], 8 C M
br .LL00 C B
.Lb01: add n = -1, n C M I
logop( r15, r10, r11) C M I
(p15) br.cond.dpnt .grt1 C B
;;
notormov( r9, r15) C M I
br .Lcj1 C B
.grt1: ld8 r16 = [up], 8 C M
ld8 r20 = [vp], 8 C M
;;
ld8 r17 = [up], 8 C M
ld8 r21 = [vp], 8 C M
mov.i ar.lc = n C I0
;;
ld8 r18 = [up], 8 C M
ld8 r22 = [vp], 8 C M
;;
ld8 r19 = [up], 8 C M
ld8 r23 = [vp], 8 C M
br.cloop.dptk .grt5 C B
;;
logop( r14, r16, r20) C M I
notormov( r9, r15) C M I
br .Lcj5 C B
.grt5: logop( r14, r16, r20) C M I
ld8 r16 = [up], 8 C M
notormov( r9, r15) C M I
ld8 r20 = [vp], 8 C M
br .LL01 C B
.Lb10: ld8 r19 = [up], 8 C M
ld8 r23 = [vp], 8 C M
(p15) br.cond.dpnt .grt2 C B
logop( r14, r10, r11) C M I
;;
logop( r15, r19, r23) C M I
notormov( r8, r14) C M I
br .Lcj2 C B
.grt2: ld8 r16 = [up], 8 C M
ld8 r20 = [vp], 8 C M
add n = -1, n C M I
;;
ld8 r17 = [up], 8 C M
ld8 r21 = [vp], 8 C M
logop( r14, r10, r11) C M I
;;
ld8 r18 = [up], 8 C M
ld8 r22 = [vp], 8 C M
mov.i ar.lc = n C I0
;;
logop( r15, r19, r23) C M I
ld8 r19 = [up], 8 C M
notormov( r8, r14) C M I
ld8 r23 = [vp], 8 C M
br.cloop.dptk .Loop C B
br .Lcj6 C B
.Lb11: ld8 r18 = [up], 8 C M
ld8 r22 = [vp], 8 C M
add n = -1, n C M I
;;
ld8 r19 = [up], 8 C M
ld8 r23 = [vp], 8 C M
logop( r15, r10, r11) C M I
(p15) br.cond.dpnt .grt3 C B
;;
logop( r14, r18, r22) C M I
notormov( r9, r15) C M I
br .Lcj3 C B
.grt3: ld8 r16 = [up], 8 C M
ld8 r20 = [vp], 8 C M
;;
ld8 r17 = [up], 8 C M
ld8 r21 = [vp], 8 C M
mov.i ar.lc = n C I0
;;
logop( r14, r18, r22) C M I
ld8 r18 = [up], 8 C M
notormov( r9, r15) C M I
ld8 r22 = [vp], 8 C M
br .LL11 C B
C *** MAIN LOOP START ***
ALIGN(32)
.Loop: st8 [rp] = r8, 8 C M
logop( r14, r16, r20) C M I
notormov( r9, r15) C M I
ld8 r16 = [up], 8 C M
ld8 r20 = [vp], 8 C M
nop.b 0
;;
.LL01: st8 [rp] = r9, 8 C M
logop( r15, r17, r21) C M I
notormov( r8, r14) C M I
ld8 r17 = [up], 8 C M
ld8 r21 = [vp], 8 C M
nop.b 0
;;
.LL00: st8 [rp] = r8, 8 C M
logop( r14, r18, r22) C M I
notormov( r9, r15) C M I
ld8 r18 = [up], 8 C M
ld8 r22 = [vp], 8 C M
nop.b 0
;;
.LL11: st8 [rp] = r9, 8 C M
logop( r15, r19, r23) C M I
notormov( r8, r14) C M I
ld8 r19 = [up], 8 C M
ld8 r23 = [vp], 8 C M
br.cloop.dptk .Loop ;; C B
C *** MAIN LOOP END ***
.Lcj6: st8 [rp] = r8, 8 C M
logop( r14, r16, r20) C M I
notormov( r9, r15) C M I
;;
.Lcj5: st8 [rp] = r9, 8 C M
logop( r15, r17, r21) C M I
notormov( r8, r14) C M I
;;
.Lcj4: st8 [rp] = r8, 8 C M
logop( r14, r18, r22) C M I
notormov( r9, r15) C M I
;;
.Lcj3: st8 [rp] = r9, 8 C M
logop( r15, r19, r23) C M I
notormov( r8, r14) C M I
;;
.Lcj2: st8 [rp] = r8, 8 C M
notormov( r9, r15) C M I
;;
.Lcj1: st8 [rp] = r9, 8 C M
mov.i ar.lc = r2 C I0
br.ret.sptk.many b0 C B
EPILOGUE()
ASM_END()
|
; void wa_stack_clear(wa_stack_t *s)
SECTION code_clib
SECTION code_adt_wa_stack
PUBLIC _wa_stack_clear
EXTERN _w_array_clear
defc _wa_stack_clear = _w_array_clear
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2011 Fabien Le Floc'h
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file trbdf2.hpp
\brief TR-BDF2 scheme for finite difference methods
*/
#ifndef quantlib_trbdf2_hpp
#define quantlib_trbdf2_hpp
#include <ql/methods/finitedifferences/finitedifferencemodel.hpp>
namespace QuantLib {
//! TR-BDF2 scheme for finite difference methods
/*! See <http://ssrn.com/abstract=1648878> for details.
In this implementation, the passed operator must be derived
from either TimeConstantOperator or TimeDependentOperator.
Also, it must implement at least the following interface:
\code
typedef ... array_type;
// copy constructor/assignment
// (these will be provided by the compiler if none is defined)
Operator(const Operator&);
Operator& operator=(const Operator&);
// inspectors
Size size();
// modifiers
void setTime(Time t);
// operator interface
array_type applyTo(const array_type&);
array_type solveFor(const array_type&);
static Operator identity(Size size);
// operator algebra
Operator operator*(Real, const Operator&);
Operator operator+(const Operator&, const Operator&);
Operator operator+(const Operator&, const Operator&);
\endcode
\warning The differential operator must be linear for
this evolver to work.
\ingroup findiff
*/
// NOTE: There is room for performance improvement especially in
// the array manipulation
template <class Operator>
class TRBDF2 {
public:
// typedefs
typedef OperatorTraits<Operator> traits;
typedef typename traits::operator_type operator_type;
typedef typename traits::array_type array_type;
typedef typename traits::bc_set bc_set;
typedef typename traits::condition_type condition_type;
// constructors
TRBDF2(const operator_type& L,
const bc_set& bcs)
: L_(L), I_(operator_type::identity(L.size())),
dt_(0.0), bcs_(bcs), alpha_(2.0-sqrt(2.0)) {}
void step(array_type& a,
Time t);
void setStep(Time dt) {
dt_ = dt;
implicitPart_ = I_ + 0.5*alpha_*dt_*L_;
explicitTrapezoidalPart_ = I_ - 0.5*alpha_*dt_*L_;
explicitBDF2PartFull_ =
-(1.0-alpha_)*(1.0-alpha_)/(alpha_*(2.0-alpha_))*I_;
explicitBDF2PartMid_ = 1.0/(alpha_*(2.0-alpha_))*I_;
}
private:
Real alpha_;
operator_type L_, I_, explicitTrapezoidalPart_,
explicitBDF2PartFull_,explicitBDF2PartMid_, implicitPart_;
Time dt_;
bc_set bcs_;
array_type aInit_;
};
// inline definitions
template <class Operator>
inline void TRBDF2<Operator>::step(array_type& a, Time t) {
Size i;
Array aInit(a.size());
for (i=0; i<a.size();i++) {
aInit[i] = a[i];
}
aInit_ = aInit;
for (i=0; i<bcs_.size(); i++)
bcs_[i]->setTime(t);
//trapezoidal explicit part
if (L_.isTimeDependent()) {
L_.setTime(t);
explicitTrapezoidalPart_ = I_ - 0.5*alpha_*dt_*L_;
}
for (i=0; i<bcs_.size(); i++)
bcs_[i]->applyBeforeApplying(explicitTrapezoidalPart_);
a = explicitTrapezoidalPart_.applyTo(a);
for (i=0; i<bcs_.size(); i++)
bcs_[i]->applyAfterApplying(a);
// trapezoidal implicit part
if (L_.isTimeDependent()) {
L_.setTime(t-dt_);
implicitPart_ = I_ + 0.5*alpha_*dt_*L_;
}
for (i=0; i<bcs_.size(); i++)
bcs_[i]->applyBeforeSolving(implicitPart_,a);
a = implicitPart_.solveFor(a);
for (i=0; i<bcs_.size(); i++)
bcs_[i]->applyAfterSolving(a);
// BDF2 explicit part
if (L_.isTimeDependent()) {
L_.setTime(t);
}
for (i=0; i<bcs_.size(); i++) {
bcs_[i]->applyBeforeApplying(explicitBDF2PartFull_);
}
array_type b0 = explicitBDF2PartFull_.applyTo(aInit_);
for (i=0; i<bcs_.size(); i++)
bcs_[i]->applyAfterApplying(b0);
for (i=0; i<bcs_.size(); i++) {
bcs_[i]->applyBeforeApplying(explicitBDF2PartMid_);
}
array_type b1 = explicitBDF2PartMid_.applyTo(a);
for (i=0; i<bcs_.size(); i++)
bcs_[i]->applyAfterApplying(b1);
a = b0+b1;
// reuse implicit part - works only for alpha=2-sqrt(2)
for (i=0; i<bcs_.size(); i++)
bcs_[i]->applyBeforeSolving(implicitPart_,a);
a = implicitPart_.solveFor(a);
for (i=0; i<bcs_.size(); i++)
bcs_[i]->applyAfterSolving(a);
}
}
#endif
|
//////////////////////////////////////////////////////////////////////////////
/// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand
/// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI
///
/// Distributed under the Boost Software License, Version 1.0
/// See accompanying file LICENSE.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt
//////////////////////////////////////////////////////////////////////////////
#ifndef NT2_TOOLBOX_GSL_SPECFUN_FUNCTION_SIMD_SSE_XOP_GSL_SF_BESSEL_J1_HPP_INCLUDED
#define NT2_TOOLBOX_GSL_SPECFUN_FUNCTION_SIMD_SSE_XOP_GSL_SF_BESSEL_J1_HPP_INCLUDED
#include <nt2/toolbox/gsl_specfun/function/simd/sse/sse4a/gsl_sf_bessel_J1.hpp>
#endif
|
# Test cases for MIPS 5-Stage pipeline
.data
.word 0,1,2,3,0x80000000,0x80000100,0x100,5,0
_start:
add $t1, $0, $0 # $t1 = 0 0
j _test0 # 4
_test0:
addi $t2, $0, 1 # $t2 = 1 8
addi $t2, $t2, 1 # $t2 = 2 12
add $t2, $t2, $t2 # $t2 = 4 16
addi $t2, $t2, -4 # $t2 = 0 20
beq $t2, $0, _next0 # if $t2 == $0: $t1++, go next testcase, else: go fail 24
j _fail # 28
_next0:
addi $t1, $t1, 1 # $t1++ 32
j _test1 # 36
_test1:
addi $0, $0, 4 # $0 += 4 40
lw $t2, 4($0) # $t2 = MEM[1] 44
lw $t3, 8($0) # $t3 = MEM[2] 48
add $t4, $t2, $t3 # 52
sw $t4, 0($0) # MEM[0] = $t4 56
lw $t5, 0($0) # $t5 = MEM[0] 60
lw $t6, 12($0) # $t6 = MEM[3] 64
beq $t5, $t6, _next1 # 68
j _fail # 72
_next1:
addi $t1, $t1, 1 # 76
j _success # 80
_fail:
j _fail # 84
_success:
j _success # if success: $t1 == 2 88
|
; A079962: Number of permutations satisfying -k <= p(i) - i <= r and p(i) - i not in I, i=1..n, with k=1, r=5, I={1,3}.
; 1,1,1,2,3,5,9,14,22,36,58,94,153,247,399,646,1045,1691,2737,4428,7164,11592,18756,30348,49105,79453,128557,208010,336567,544577,881145,1425722,2306866,3732588,6039454,9772042,15811497,25583539,41395035
mov $1,4
mov $3,6
lpb $0
sub $0,1
mov $2,$1
mov $1,$3
add $3,$2
lpe
sub $1,4
div $1,8
add $1,1
mov $0,$1
|
SECTION code_clib
SECTION code_fp_math48
PUBLIC _fmin_callee
EXTERN cm48_sdccix_fmin_callee
defc _fmin_callee = cm48_sdccix_fmin_callee
|
; A097708: Sum of prime length repunits; sum_k=1..n (r(p(k))), where r()= A002275 and p(k) is the k-th prime.
; Submitted by Jon Maiga
; 0,11,122,11233,1122344,11112233455,1122223344566,11112233334455677,1122223344445566788,11112233334455556677899,11111122223344445566667789010,1122222233334455556677778900121
lpb $0
sub $0,1
mov $2,$0
max $2,0
seq $2,31974 ; 1 repeated prime(n) times.
add $1,$2
lpe
mov $0,$1
|
/*
* Copyright (c) 2010-2012 OTClient <https://github.com/edubart/otclient>
*
* 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 "streamsoundsource.h"
#include "soundbuffer.h"
#include "soundfile.h"
#include <framework/util/databuffer.h>
StreamSoundSource::StreamSoundSource()
{
for(auto& buffer : m_buffers)
buffer = SoundBufferPtr(new SoundBuffer);
m_downMix = NoDownMix;
}
StreamSoundSource::~StreamSoundSource()
{
stop();
}
void StreamSoundSource::setSoundFile(const SoundFilePtr& soundFile)
{
m_soundFile = soundFile;
}
void StreamSoundSource::play()
{
if(!m_soundFile) {
logError("there is not sound file to play the stream");
return;
}
queueBuffers();
SoundSource::play();
}
void StreamSoundSource::stop()
{
SoundSource::stop();
unqueueBuffers();
}
void StreamSoundSource::queueBuffers()
{
ALint queued;
alGetSourcei(m_sourceId, AL_BUFFERS_QUEUED, &queued);
for(int i = 0; i < STREAM_FRAGMENTS - queued; ++i) {
if(!fillBufferAndQueue(m_buffers[i]->getBufferId()))
break;
}
}
void StreamSoundSource::unqueueBuffers()
{
ALint queued;
alGetSourcei(m_sourceId, AL_BUFFERS_QUEUED, &queued);
for(int i = 0; i < queued; ++i) {
ALuint buffer;
alSourceUnqueueBuffers(m_sourceId, 1, &buffer);
}
}
void StreamSoundSource::update()
{
SoundSource::update();
ALint processed = 0;
alGetSourcei(m_sourceId, AL_BUFFERS_PROCESSED, &processed);
for(ALint i = 0; i < processed; ++i) {
ALuint buffer;
alSourceUnqueueBuffers(m_sourceId, 1, &buffer);
//SoundManager::check_al_error("Couldn't unqueue audio buffer: ");
if(!fillBufferAndQueue(buffer))
break;
}
if(!isPlaying()) {
if(processed == 0 || !m_looping)
return;
logTraceError("restarting audio source because of buffer underrun");
play();
}
}
bool StreamSoundSource::fillBufferAndQueue(ALuint buffer)
{
// fill buffer
static DataBuffer<char> bufferData(2*STREAM_FRAGMENT_SIZE);
ALenum format = m_soundFile->getSampleFormat();
int maxRead = STREAM_FRAGMENT_SIZE;
if(m_downMix != NoDownMix)
maxRead *= 2;
int bytesRead = 0;
do {
bytesRead += m_soundFile->read(&bufferData[bytesRead], maxRead - bytesRead);
// end of sound file
if(bytesRead < maxRead) {
if(m_looping)
m_soundFile->reset();
else
break;
}
} while(bytesRead < maxRead);
if(bytesRead > 0) {
if(m_downMix != NoDownMix) {
if(format == AL_FORMAT_STEREO16) {
assert(bytesRead % 2 == 0);
bytesRead /= 2;
uint16_t *data = (uint16_t*)bufferData.data();
for(int i=0;i<bytesRead/2;i++)
data[i] = data[2*i + (m_downMix == DownMixLeft ? 0 : 1)];
format = AL_FORMAT_MONO16;
}
}
alBufferData(buffer, format, &bufferData[0], bytesRead, m_soundFile->getRate());
ALenum err = alGetError();
if(err != AL_NO_ERROR)
logError("unable to refill audio buffer for '", m_soundFile->getName(), "': ", alGetString(err));
alSourceQueueBuffers(m_sourceId, 1, &buffer);
err = alGetError();
if(err != AL_NO_ERROR)
logError("unable to queue audio buffer for '", m_soundFile->getName(), "': ", alGetString(err));
}
// return false if there aren't more buffers to fill
return bytesRead >= STREAM_FRAGMENT_SIZE;
}
void StreamSoundSource::downMix(StreamSoundSource::DownMix downMix)
{
if(!m_soundFile) {
logError("down mix must be set after setting a sound file");
return;
}
if(m_soundFile->getSampleFormat() != AL_FORMAT_STEREO16) {
logError("can only downmix 16 bit stereo audio files");
return;
}
m_downMix = downMix;
}
|
/**
* @file methods/ann/loss_functions/mean_squared_logarithmic_error_impl.hpp
* @author Saksham Rastogi
*
* Implementation of the mean squared logarithmic error function.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_METHODS_ANN_LOSS_FUNCTION_MEAN_SQUARED_LOGARITHMIC_ERROR_IMPL_HPP
#define MLPACK_METHODS_ANN_LOSS_FUNCTION_MEAN_SQUARED_LOGARITHMIC_ERROR_IMPL_HPP
// In case it hasn't yet been included.
#include "mean_squared_logarithmic_error.hpp"
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
template<typename InputDataType, typename OutputDataType>
MeanSquaredLogarithmicError<InputDataType, OutputDataType>
::MeanSquaredLogarithmicError()
{
// Nothing to do here.
}
template<typename InputDataType, typename OutputDataType>
template<typename PredictionType, typename TargetType>
typename PredictionType::elem_type
MeanSquaredLogarithmicError<InputDataType, OutputDataType>::Forward(
const PredictionType& prediction,
const TargetType& target)
{
return arma::accu(arma::square(arma::log(1. + target) -
arma::log(1. + prediction))) / target.n_cols;
}
template<typename InputDataType, typename OutputDataType>
template<typename PredictionType, typename TargetType, typename LossType>
void MeanSquaredLogarithmicError<InputDataType, OutputDataType>::Backward(
const PredictionType& prediction,
const TargetType& target,
LossType& loss)
{
loss = 2 * (arma::log(1. + prediction) - arma::log(1. + target)) /
((1. + prediction) * target.n_cols);
}
template<typename InputDataType, typename OutputDataType>
template<typename Archive>
void MeanSquaredLogarithmicError<InputDataType, OutputDataType>::serialize(
Archive& /* ar */,
const uint32_t /* version */)
{
// Nothing to do here.
}
} // namespace ann
} // namespace mlpack
#endif
|
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
/// 416. Partition Equal Subset Sum
/// https://leetcode.com/problems/partition-equal-subset-sum/description/
/// 记忆化搜索
/// 时间复杂度: O(len(nums) * O(sum(nums)))
/// 空间复杂度: O(len(nums) * O(sum(nums)))
class Solution {
private:
// memo[i][c] 表示使用索引为[0...i]的这些元素,是否可以完全填充一个容量为c的背包
// -1 表示为未计算; 0 表示不可以填充; 1 表示可以填充
vector<vector<int>> memo;
// 使用nums[0...index], 是否可以完全填充一个容量为sum的背包
bool tryPartition(const vector<int> &nums, int index, int sum){
if(sum == 0)
return true;
if(sum < 0 || index < 0)
return false;
if(memo[index][sum] != -1)
return memo[index][sum] == 1;
memo[index][sum] = (tryPartition(nums, index - 1, sum) ||
tryPartition(nums, index - 1, sum - nums[index])) ? 1 : 0;
return memo[index][sum] == 1;
}
public:
bool canPartition(vector<int>& nums) {
int sum = 0;
for(int i = 0 ; i < nums.size() ; i ++){
assert(nums[i] > 0);
sum += nums[i];
}
if(sum % 2)
return false;
memo.clear();
for(int i = 0 ; i < nums.size() ; i ++)
memo.push_back(vector<int>(sum / 2 + 1, -1));
return tryPartition(nums, nums.size() - 1, sum / 2);
}
};
int main() {
int nums1[] = {1, 5, 11, 5};
vector<int> vec1(nums1, nums1 + sizeof(nums1)/sizeof(int));
if(Solution().canPartition(vec1))
cout << "true" << endl;
else
cout << "false" << endl;
int nums2[] = {1, 2, 3, 5};
vector<int> vec2(nums2, nums2 + sizeof(nums2)/sizeof(int));
if(Solution().canPartition(vec2))
cout << "true" << endl;
else
cout << "false" << endl;
return 0;
} |
.data # Variables
myMessage: .asciiz "Hello World\n"
.text # Instructions
li $v0, 4
la $a0, myMessage
syscall |
; A036781: a(n) = n + Sum_{k=0..n} k!.
; 1,3,6,13,38,159,880,5921,46242,409123,4037924,43954725,522956326,6749977127,93928268328,1401602636329,22324392524330,378011820620331,6780385526348332,128425485935180333,2561327494111820334,53652269665821260335,1177652997443428940336,27029669736328405580337,647478071469567844940338,16158688114800553828940339,419450149241406189412940340,11308319599659758350180940341,316196664211373618851684940342,9157958657951075573395300940343,274410818470142134209703780940344,8497249472648064951935266660940345
mov $1,1
mov $2,$0
mov $3,$0
lpb $2
mul $1,$2
add $1,1
sub $2,1
lpe
add $1,$3
mov $0,$1
|
; A199211: 11*4^n+1.
; 12,45,177,705,2817,11265,45057,180225,720897,2883585,11534337,46137345,184549377,738197505,2952790017,11811160065,47244640257,188978561025,755914244097,3023656976385,12094627905537,48378511622145,193514046488577,774056185954305,3096224743817217,12384898975268865,49539595901075457,198158383604301825,792633534417207297,3170534137668829185,12682136550675316737,50728546202701266945,202914184810805067777,811656739243220271105,3246626956972881084417,12986507827891524337665,51946031311566097350657
mov $1,4
pow $1,$0
mul $1,11
add $1,1
mov $0,$1
|
; A093719: a(n) = (n mod 2)^(n mod 3).
; 1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1
mov $1,$0
mod $0,3
mod $1,2
pow $1,$0
|
;===============================================================================
; Copyright 2015-2018 Intel Corporation
; All Rights Reserved.
;
; If this software was obtained under the Intel Simplified Software License,
; the following terms apply:
;
; The source code, information and material ("Material") contained herein is
; owned by Intel Corporation or its suppliers or licensors, and title to such
; Material remains with Intel Corporation or its suppliers or licensors. The
; Material contains proprietary information of Intel or its suppliers and
; licensors. The Material is protected by worldwide copyright laws and treaty
; provisions. No part of the Material may be used, copied, reproduced,
; modified, published, uploaded, posted, transmitted, distributed or disclosed
; in any way without Intel's prior express written permission. No license under
; any patent, copyright or other intellectual property rights in the Material
; is granted to or conferred upon you, either expressly, by implication,
; inducement, estoppel or otherwise. Any license under such intellectual
; property rights must be express and approved by Intel in writing.
;
; Unless otherwise agreed by Intel in writing, you may not remove or alter this
; notice or any other notice embedded in Materials by Intel or Intel's
; suppliers or licensors in any way.
;
;
; If this software was obtained under the Apache License, Version 2.0 (the
; "License"), the following terms apply:
;
; You may not use this file except in compliance with the License. You may
; obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
;
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
; WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;
; See the License for the specific language governing permissions and
; limitations under the License.
;===============================================================================
;
;
; Purpose: Cryptography Primitive.
; secp p224r1 specific implementation
;
include asmdefs.inc
include ia_32e.inc
IF _IPP32E GE _IPP32E_M7
_xEMULATION_ = 1
_ADCX_ADOX_ = 1
.LIST
IPPCODE SEGMENT 'CODE' ALIGN (IPP_ALIGN_FACTOR)
ALIGN IPP_ALIGN_FACTOR
;; The p224r1 polynomial
Lpoly DQ 00000000000000001h,0ffffffff00000000h,0ffffffffffffffffh,000000000ffffffffh
;; mont(1)
;; ffffffff00000000 ffffffffffffffff 0000000000000000 0000000000000000
;; 2^(2*224) mod P precomputed for p224r1 polynomial
LRR DQ 0ffffffff00000001h,0ffffffff00000000h,0fffffffe00000000h,000000000ffffffffh
LOne DD 1,1,1,1,1,1,1,1
LTwo DD 2,2,2,2,2,2,2,2
LThree DD 3,3,3,3,3,3,3,3
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p224r1_mul_by_2(uint64_t res[4], uint64_t a[4]);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ALIGN IPP_ALIGN_FACTOR
IPPASM p224r1_mul_by_2 PROC PUBLIC FRAME
USES_GPR rsi,rdi,r12,r13
LOCAL_FRAME = 0
USES_XMM
COMP_ABI 2
a0 equ r8
a1 equ r9
a2 equ r10
a3 equ r11
t0 equ rax
t1 equ rdx
t2 equ rcx
t3 equ r12
t4 equ r13
xor t4, t4
mov a0, qword ptr[rsi+sizeof(qword)*0]
mov a1, qword ptr[rsi+sizeof(qword)*1]
mov a2, qword ptr[rsi+sizeof(qword)*2]
mov a3, qword ptr[rsi+sizeof(qword)*3]
shld t4, a3, 1
shld a3, a2, 1
shld a2, a1, 1
shld a1, a0, 1
shl a0, 1
mov t0, a0
mov t1, a1
mov t2, a2
mov t3, a3
sub t0, qword ptr Lpoly+sizeof(qword)*0
sbb t1, qword ptr Lpoly+sizeof(qword)*1
sbb t2, qword ptr Lpoly+sizeof(qword)*2
sbb t3, qword ptr Lpoly+sizeof(qword)*3
sbb t4, 0
cmovz a0, t0
cmovz a1, t1
cmovz a2, t2
cmovz a3, t3
mov qword ptr[rdi+sizeof(qword)*0], a0
mov qword ptr[rdi+sizeof(qword)*1], a1
mov qword ptr[rdi+sizeof(qword)*2], a2
mov qword ptr[rdi+sizeof(qword)*3], a3
REST_XMM
REST_GPR
ret
IPPASM p224r1_mul_by_2 ENDP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p224r1_div_by_2(uint64_t res[4], uint64_t a[4]);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ALIGN IPP_ALIGN_FACTOR
IPPASM p224r1_div_by_2 PROC PUBLIC FRAME
USES_GPR rsi,rdi,r12,r13,r14
LOCAL_FRAME = 0
USES_XMM
COMP_ABI 2
a0 equ r8
a1 equ r9
a2 equ r10
a3 equ r11
t0 equ rax
t1 equ rdx
t2 equ rcx
t3 equ r12
t4 equ r13
mov a0, qword ptr[rsi+sizeof(qword)*0]
mov a1, qword ptr[rsi+sizeof(qword)*1]
mov a2, qword ptr[rsi+sizeof(qword)*2]
mov a3, qword ptr[rsi+sizeof(qword)*3]
xor t4, t4
xor r14, r14
mov t0, a0
mov t1, a1
mov t2, a2
mov t3, a3
add t0, qword ptr Lpoly+sizeof(qword)*0
adc t1, qword ptr Lpoly+sizeof(qword)*1
adc t2, qword ptr Lpoly+sizeof(qword)*2
adc t3, qword ptr Lpoly+sizeof(qword)*3
adc t4, 0
test a0, 1
cmovnz a0, t0
cmovnz a1, t1
cmovnz a2, t2
cmovnz a3, t3
cmovnz r14,t4
shrd a0, a1, 1
shrd a1, a2, 1
shrd a2, a3, 1
shrd a3, r14,1
mov qword ptr[rdi+sizeof(qword)*0], a0
mov qword ptr[rdi+sizeof(qword)*1], a1
mov qword ptr[rdi+sizeof(qword)*2], a2
mov qword ptr[rdi+sizeof(qword)*3], a3
REST_XMM
REST_GPR
ret
IPPASM p224r1_div_by_2 ENDP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p224r1_mul_by_3(uint64_t res[4], uint64_t a[4]);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ALIGN IPP_ALIGN_FACTOR
IPPASM p224r1_mul_by_3 PROC PUBLIC FRAME
USES_GPR rsi,rdi,r12,r13
LOCAL_FRAME = 0
USES_XMM
COMP_ABI 2
a0 equ r8
a1 equ r9
a2 equ r10
a3 equ r11
t0 equ rax
t1 equ rdx
t2 equ rcx
t3 equ r12
t4 equ r13
xor t4, t4
mov a0, qword ptr[rsi+sizeof(qword)*0]
mov a1, qword ptr[rsi+sizeof(qword)*1]
mov a2, qword ptr[rsi+sizeof(qword)*2]
mov a3, qword ptr[rsi+sizeof(qword)*3]
shld t4, a3, 1
shld a3, a2, 1
shld a2, a1, 1
shld a1, a0, 1
shl a0, 1
mov t0, a0
mov t1, a1
mov t2, a2
mov t3, a3
sub t0, qword ptr Lpoly+sizeof(qword)*0
sbb t1, qword ptr Lpoly+sizeof(qword)*1
sbb t2, qword ptr Lpoly+sizeof(qword)*2
sbb t3, qword ptr Lpoly+sizeof(qword)*3
sbb t4, 0
cmovz a0, t0
cmovz a1, t1
cmovz a2, t2
cmovz a3, t3
xor t4, t4
add a0, qword ptr[rsi+sizeof(qword)*0]
adc a1, qword ptr[rsi+sizeof(qword)*1]
adc a2, qword ptr[rsi+sizeof(qword)*2]
adc a3, qword ptr[rsi+sizeof(qword)*3]
adc t4, 0
mov t0, a0
mov t1, a1
mov t2, a2
mov t3, a3
sub t0, qword ptr Lpoly+sizeof(qword)*0
sbb t1, qword ptr Lpoly+sizeof(qword)*1
sbb t2, qword ptr Lpoly+sizeof(qword)*2
sbb t3, qword ptr Lpoly+sizeof(qword)*3
sbb t4, 0
cmovz a0, t0
cmovz a1, t1
cmovz a2, t2
cmovz a3, t3
mov qword ptr[rdi+sizeof(qword)*0], a0
mov qword ptr[rdi+sizeof(qword)*1], a1
mov qword ptr[rdi+sizeof(qword)*2], a2
mov qword ptr[rdi+sizeof(qword)*3], a3
REST_XMM
REST_GPR
ret
IPPASM p224r1_mul_by_3 ENDP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p224r1_add(uint64_t res[4], uint64_t a[4], uint64_t b[4]);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ALIGN IPP_ALIGN_FACTOR
IPPASM p224r1_add PROC PUBLIC FRAME
USES_GPR rsi,rdi,r12,r13
LOCAL_FRAME = 0
USES_XMM
COMP_ABI 3
a0 equ r8
a1 equ r9
a2 equ r10
a3 equ r11
t0 equ rax
t1 equ rdx
t2 equ rcx
t3 equ r12
t4 equ r13
xor t4, t4
mov a0, qword ptr[rsi+sizeof(qword)*0]
mov a1, qword ptr[rsi+sizeof(qword)*1]
mov a2, qword ptr[rsi+sizeof(qword)*2]
mov a3, qword ptr[rsi+sizeof(qword)*3]
add a0, qword ptr[rdx+sizeof(qword)*0]
adc a1, qword ptr[rdx+sizeof(qword)*1]
adc a2, qword ptr[rdx+sizeof(qword)*2]
adc a3, qword ptr[rdx+sizeof(qword)*3]
adc t4, 0
mov t0, a0
mov t1, a1
mov t2, a2
mov t3, a3
sub t0, qword ptr Lpoly+sizeof(qword)*0
sbb t1, qword ptr Lpoly+sizeof(qword)*1
sbb t2, qword ptr Lpoly+sizeof(qword)*2
sbb t3, qword ptr Lpoly+sizeof(qword)*3
sbb t4, 0
cmovz a0, t0
cmovz a1, t1
cmovz a2, t2
cmovz a3, t3
mov qword ptr[rdi+sizeof(qword)*0], a0
mov qword ptr[rdi+sizeof(qword)*1], a1
mov qword ptr[rdi+sizeof(qword)*2], a2
mov qword ptr[rdi+sizeof(qword)*3], a3
REST_XMM
REST_GPR
ret
IPPASM p224r1_add ENDP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p224r1_sub(uint64_t res[4], uint64_t a[4], uint64_t b[4]);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ALIGN IPP_ALIGN_FACTOR
IPPASM p224r1_sub PROC PUBLIC FRAME
USES_GPR rsi,rdi,r12,r13
LOCAL_FRAME = 0
USES_XMM
COMP_ABI 3
a0 equ r8
a1 equ r9
a2 equ r10
a3 equ r11
t0 equ rax
t1 equ rdx
t2 equ rcx
t3 equ r12
t4 equ r13
xor t4, t4
mov a0, qword ptr[rsi+sizeof(qword)*0]
mov a1, qword ptr[rsi+sizeof(qword)*1]
mov a2, qword ptr[rsi+sizeof(qword)*2]
mov a3, qword ptr[rsi+sizeof(qword)*3]
sub a0, qword ptr[rdx+sizeof(qword)*0]
sbb a1, qword ptr[rdx+sizeof(qword)*1]
sbb a2, qword ptr[rdx+sizeof(qword)*2]
sbb a3, qword ptr[rdx+sizeof(qword)*3]
sbb t4, 0
mov t0, a0
mov t1, a1
mov t2, a2
mov t3, a3
add t0, qword ptr Lpoly+sizeof(qword)*0
adc t1, qword ptr Lpoly+sizeof(qword)*1
adc t2, qword ptr Lpoly+sizeof(qword)*2
adc t3, qword ptr Lpoly+sizeof(qword)*3
test t4, t4
cmovnz a0, t0
cmovnz a1, t1
cmovnz a2, t2
cmovnz a3, t3
mov qword ptr[rdi+sizeof(qword)*0], a0
mov qword ptr[rdi+sizeof(qword)*1], a1
mov qword ptr[rdi+sizeof(qword)*2], a2
mov qword ptr[rdi+sizeof(qword)*3], a3
REST_XMM
REST_GPR
ret
IPPASM p224r1_sub ENDP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p224r1_neg(uint64_t res[4], uint64_t a[4]);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ALIGN IPP_ALIGN_FACTOR
IPPASM p224r1_neg PROC PUBLIC FRAME
USES_GPR rsi,rdi,r12,r13
LOCAL_FRAME = 0
USES_XMM
COMP_ABI 2
a0 equ r8
a1 equ r9
a2 equ r10
a3 equ r11
t0 equ rax
t1 equ rdx
t2 equ rcx
t3 equ r12
t4 equ r13
xor t4, t4
xor a0, a0
xor a1, a1
xor a2, a2
xor a3, a3
sub a0, qword ptr[rsi+sizeof(qword)*0]
sbb a1, qword ptr[rsi+sizeof(qword)*1]
sbb a2, qword ptr[rsi+sizeof(qword)*2]
sbb a3, qword ptr[rsi+sizeof(qword)*3]
sbb t4, 0
mov t0, a0
mov t1, a1
mov t2, a2
mov t3, a3
add t0, qword ptr Lpoly+sizeof(qword)*0
adc t1, qword ptr Lpoly+sizeof(qword)*1
adc t2, qword ptr Lpoly+sizeof(qword)*2
adc t3, qword ptr Lpoly+sizeof(qword)*3
test t4, t4
cmovnz a0, t0
cmovnz a1, t1
cmovnz a2, t2
cmovnz a3, t3
mov qword ptr[rdi+sizeof(qword)*0], a0
mov qword ptr[rdi+sizeof(qword)*1], a1
mov qword ptr[rdi+sizeof(qword)*2], a2
mov qword ptr[rdi+sizeof(qword)*3], a3
REST_XMM
REST_GPR
ret
IPPASM p224r1_neg ENDP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p224r1_mul_montl(uint64_t res[4], uint64_t a[4], uint64_t b[4]);
; void p224r1_mul_montx(uint64_t res[4], uint64_t a[4], uint64_t b[4]);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; was working on GFp functionality the problem (in reduction spep) has been found
;; 1) "sqr" impementation has been changed by "mul"
;; 2) fortunately "mont_back" stay as is because of operand zero extensioned
; on entry p5=0
; on exit p0=0
;
p224r1_prod_redstep MACRO p4,p3,p2,p1,p0
neg p0
mov t2, p0
mov t3, p0
xor t0, t0
xor t1, t1
shr t3, 32
shl t2, 32
sub t0, t2
sbb t1, t3
sbb t2, 0
sbb t3, 0
neg p0
adc p1, t0
adc p2, t1
adc p3, t2
adc p4, t3
ENDM
ALIGN IPP_ALIGN_FACTOR
p224r1_mmull:
acc0 equ r8
acc1 equ r9
acc2 equ r10
acc3 equ r11
acc4 equ r12
acc5 equ r13
acc6 equ r14
acc7 equ r15
t0 equ rax
t1 equ rdx
t2 equ rcx
t3 equ rbp
t4 equ rbx
; rdi assumed as result
aPtr equ rsi
bPtr equ rbx
xor acc5, acc5
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; * b[0]
mov rax, qword ptr[bPtr+sizeof(qword)*0]
mul qword ptr[aPtr+sizeof(qword)*0]
mov acc0, rax
mov acc1, rdx
mov rax, qword ptr[bPtr+sizeof(qword)*0]
mul qword ptr[aPtr+sizeof(qword)*1]
add acc1, rax
adc rdx, 0
mov acc2, rdx
mov rax, qword ptr[bPtr+sizeof(qword)*0]
mul qword ptr[aPtr+sizeof(qword)*2]
add acc2, rax
adc rdx, 0
mov acc3, rdx
mov rax, qword ptr[bPtr+sizeof(qword)*0]
mul qword ptr[aPtr+sizeof(qword)*3]
add acc3, rax
adc rdx, 0
mov acc4, rdx
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; reduction step 0
p224r1_prod_redstep acc4,acc3,acc2,acc1,acc0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; * b[1]
mov rax, qword ptr[bPtr+sizeof(qword)*1]
mul qword ptr[aPtr+sizeof(qword)*0]
add acc1, rax
adc rdx, 0
mov rcx, rdx
mov rax, qword ptr[bPtr+sizeof(qword)*1]
mul qword ptr[aPtr+sizeof(qword)*1]
add acc2, rcx
adc rdx, 0
add acc2, rax
adc rdx, 0
mov rcx, rdx
mov rax, qword ptr[bPtr+sizeof(qword)*1]
mul qword ptr[aPtr+sizeof(qword)*2]
add acc3, rcx
adc rdx, 0
add acc3, rax
adc rdx, 0
mov rcx, rdx
mov rax, qword ptr[bPtr+sizeof(qword)*1]
mul qword ptr[aPtr+sizeof(qword)*3]
add acc4, rcx
adc rdx, 0
add acc4, rax
adc rdx, 0
mov acc5, rdx
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; reduction step 1
p224r1_prod_redstep acc5,acc4,acc3,acc2,acc1
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; * b[2]
mov rax, qword ptr[bPtr+sizeof(qword)*2]
mul qword ptr[aPtr+sizeof(qword)*0]
add acc2, rax
adc rdx, 0
mov rcx, rdx
mov rax, qword ptr[bPtr+sizeof(qword)*2]
mul qword ptr[aPtr+sizeof(qword)*1]
add acc3, rcx
adc rdx, 0
add acc3, rax
adc rdx, 0
mov rcx, rdx
mov rax, qword ptr[bPtr+sizeof(qword)*2]
mul qword ptr[aPtr+sizeof(qword)*2]
add acc4, rcx
adc rdx, 0
add acc4, rax
adc rdx, 0
mov rcx, rdx
mov rax, qword ptr[bPtr+sizeof(qword)*2]
mul qword ptr[aPtr+sizeof(qword)*3]
add acc5, rcx
adc rdx, 0
add acc5, rax
adc rdx, 0
mov acc6, rdx
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; reduction step 2
p224r1_prod_redstep acc6,acc5,acc4,acc3,acc2
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; * b[3]
mov rax, qword ptr[bPtr+sizeof(qword)*3]
mul qword ptr[aPtr+sizeof(qword)*0]
add acc3, rax
adc rdx, 0
mov rcx, rdx
mov rax, qword ptr[bPtr+sizeof(qword)*3]
mul qword ptr[aPtr+sizeof(qword)*1]
add acc4, rcx
adc rdx, 0
add acc4, rax
adc rdx, 0
mov rcx, rdx
mov rax, qword ptr[bPtr+sizeof(qword)*3]
mul qword ptr[aPtr+sizeof(qword)*2]
add acc5, rcx
adc rdx, 0
add acc5, rax
adc rdx, 0
mov rcx, rdx
mov rax, qword ptr[bPtr+sizeof(qword)*3]
mul qword ptr[aPtr+sizeof(qword)*3]
add acc6, rcx
adc rdx, 0
add acc6, rax
adc rdx, 0
mov acc7, rdx
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; reduction step 3 (final)
p224r1_prod_redstep acc7,acc6,acc5,acc4,acc3
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov t0, qword ptr Lpoly+sizeof(qword)*0
mov t1, qword ptr Lpoly+sizeof(qword)*1
mov t2, qword ptr Lpoly+sizeof(qword)*2
mov t3, qword ptr Lpoly+sizeof(qword)*3
mov acc0, acc4 ;; copy reducted result
mov acc1, acc5
mov acc2, acc6
mov acc3, acc7
sub acc4, t0 ;; test if it exceeds prime value
sbb acc5, t1
sbb acc6, t2
sbb acc7, t3
cmovc acc4, acc0
cmovc acc5, acc1
cmovc acc6, acc2
cmovc acc7, acc3
mov qword ptr[rdi+sizeof(qword)*0], acc4
mov qword ptr[rdi+sizeof(qword)*1], acc5
mov qword ptr[rdi+sizeof(qword)*2], acc6
mov qword ptr[rdi+sizeof(qword)*3], acc7
ret
IF _IPP32E GE _IPP32E_L9
ALIGN IPP_ALIGN_FACTOR
p224r1_mmulx:
acc0 equ r8
acc1 equ r9
acc2 equ r10
acc3 equ r11
acc4 equ r12
acc5 equ r13
acc6 equ r14
acc7 equ r15
t0 equ rax
t1 equ rdx
t2 equ rcx
t3 equ rbp
t4 equ rbx
; rdi assumed as result
aPtr equ rsi
bPtr equ rbx
xor acc5, acc5
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; * b[0]
mov rdx, qword ptr[bPtr+sizeof(qword)*0]
mulx acc1,acc0, qword ptr[aPtr+sizeof(qword)*0]
mulx acc2,t2, qword ptr[aPtr+sizeof(qword)*1]
add acc1,t2
mulx acc3,t2, qword ptr[aPtr+sizeof(qword)*2]
adc acc2,t2
mulx acc4,t2, qword ptr[aPtr+sizeof(qword)*3]
adc acc3,t2
adc acc4,0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; reduction step 0
p224r1_prod_redstep acc4,acc3,acc2,acc1,acc0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; * b[1]
mov rdx, qword ptr[bPtr+sizeof(qword)*1]
xor t0, t0
mulx t3, t2, qword ptr[aPtr+sizeof(qword)*0]
adcx %acc1, t2
adox %acc2, t3
mulx t3, t2, qword ptr[aPtr+sizeof(qword)*1]
adcx %acc2, t2
adox %acc3, t3
mulx t3, t2, qword ptr[aPtr+sizeof(qword)*2]
adcx %acc3, t2
adox %acc4, t3
mulx acc5, t2, qword ptr[aPtr+sizeof(qword)*3]
adcx %acc4, t2
adox %acc5, t0
adc acc5, 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; reduction step 1
p224r1_prod_redstep acc5,acc4,acc3,acc2,acc1
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; * b[2]
mov rdx, qword ptr[bPtr+sizeof(qword)*2]
xor t0, t0
mulx t3, t2, qword ptr[aPtr+sizeof(qword)*0]
adcx %acc2, t2
adox %acc3, t3
mulx t3, t2, qword ptr[aPtr+sizeof(qword)*1]
adcx %acc3, t2
adox %acc4, t3
mulx t3, t2, qword ptr[aPtr+sizeof(qword)*2]
adcx %acc4, t2
adox %acc5, t3
mulx acc6, t2, qword ptr[aPtr+sizeof(qword)*3]
adcx %acc5, t2
adox %acc6, t0
adc acc6, 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; reduction step 2
p224r1_prod_redstep acc6,acc5,acc4,acc3,acc2
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; * b[3]
mov rdx, qword ptr[bPtr+sizeof(qword)*3]
xor t0, t0
mulx t3, t2, qword ptr[aPtr+sizeof(qword)*0]
adcx %acc3, t2
adox %acc4, t3
mulx t3, t2, qword ptr[aPtr+sizeof(qword)*1]
adcx %acc4, t2
adox %acc5, t3
mulx t3, t2, qword ptr[aPtr+sizeof(qword)*2]
adcx %acc5, t2
adox %acc6, t3
mulx acc7, t2, qword ptr[aPtr+sizeof(qword)*3]
adcx %acc6, t2
adox %acc7, t0
adc acc7, 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; reduction step 3 (final)
p224r1_prod_redstep acc7,acc6,acc5,acc4,acc3
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov t0, qword ptr Lpoly+sizeof(qword)*0
mov t1, qword ptr Lpoly+sizeof(qword)*1
mov t2, qword ptr Lpoly+sizeof(qword)*2
mov t3, qword ptr Lpoly+sizeof(qword)*3
mov acc0, acc4 ;; copy reducted result
mov acc1, acc5
mov acc2, acc6
mov acc3, acc7
sub acc4, t0 ;; test if it exceeds prime value
sbb acc5, t1
sbb acc6, t2
sbb acc7, t3
cmovc acc4, acc0
cmovc acc5, acc1
cmovc acc6, acc2
cmovc acc7, acc3
mov qword ptr[rdi+sizeof(qword)*0], acc4
mov qword ptr[rdi+sizeof(qword)*1], acc5
mov qword ptr[rdi+sizeof(qword)*2], acc6
mov qword ptr[rdi+sizeof(qword)*3], acc7
ret
ENDIF
IPPASM p224r1_mul_montl PROC PUBLIC FRAME
USES_GPR rbp,rbx, rsi,rdi, r12,r13,r14,r15
LOCAL_FRAME = 0
USES_XMM
COMP_ABI 3
bPtr equ rbx
mov bPtr, rdx
call p224r1_mmull
REST_XMM
REST_GPR
ret
IPPASM p224r1_mul_montl ENDP
IF _IPP32E GE _IPP32E_L9
ALIGN IPP_ALIGN_FACTOR
IPPASM p224r1_mul_montx PROC PUBLIC FRAME
USES_GPR rbp,rbx, rsi,rdi,r12,r13,r14,r15
LOCAL_FRAME = 0
USES_XMM
COMP_ABI 3
bPtr equ rbx
mov bPtr, rdx
call p224r1_mmulx
REST_XMM
REST_GPR
ret
IPPASM p224r1_mul_montx ENDP
ENDIF ;; _IPP32E_L9
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p224r1_to_mont(uint64_t res[4], uint64_t a[4]);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ALIGN IPP_ALIGN_FACTOR
IPPASM p224r1_to_mont PROC PUBLIC FRAME
USES_GPR rbp,rbx, rsi,rdi,r12,r13,r14,r15
LOCAL_FRAME = 0
USES_XMM
COMP_ABI 2
lea rbx, LRR
call p224r1_mmull
REST_XMM
REST_GPR
ret
IPPASM p224r1_to_mont ENDP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p224r1_sqr_montl(uint64_t res[4], uint64_t a[4]);
; void p224r1_sqr_montx(uint64_t res[4], uint64_t a[4]);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ALIGN IPP_ALIGN_FACTOR
IPPASM p224r1_sqr_montl PROC PUBLIC FRAME
USES_GPR rbp,rbx, rsi,rdi,r12,r13,r14,r15
LOCAL_FRAME = 0
USES_XMM
COMP_ABI 2
mov rbx, rsi
call p224r1_mmull
REST_XMM
REST_GPR
ret
IPPASM p224r1_sqr_montl ENDP
IF _IPP32E GE _IPP32E_L9
ALIGN IPP_ALIGN_FACTOR
IPPASM p224r1_sqr_montx PROC PUBLIC FRAME
USES_GPR rbp,rbx, rsi,rdi,r12,r13,r14,r15
LOCAL_FRAME = 0
USES_XMM
COMP_ABI 2
mov rbx, rsi
call p224r1_mmulx
REST_XMM
REST_GPR
ret
IPPASM p224r1_sqr_montx ENDP
ENDIF ;; _IPP32E_L9
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p224r1_mont_back(uint64_t res[4], uint64_t a[4]);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ALIGN IPP_ALIGN_FACTOR
IPPASM p224r1_mont_back PROC PUBLIC FRAME
USES_GPR rsi,rdi,r12,r13,r14,r15
LOCAL_FRAME = 0
USES_XMM
COMP_ABI 2
acc0 equ r8
acc1 equ r9
acc2 equ r10
acc3 equ r11
acc4 equ r12
acc5 equ r13
acc6 equ r14
acc7 equ r15
t0 equ rax
t1 equ rdx
t2 equ rcx
t3 equ rsi
mov acc0, qword ptr[rsi+sizeof(qword)*0]
mov acc1, qword ptr[rsi+sizeof(qword)*1]
mov acc2, qword ptr[rsi+sizeof(qword)*2]
mov acc3, qword ptr[rsi+sizeof(qword)*3]
xor acc4, acc4
xor acc5, acc5
xor acc6, acc6
xor acc7, acc7
p224r1_prod_redstep acc4,acc3,acc2,acc1,acc0
p224r1_prod_redstep acc5,acc4,acc3,acc2,acc1
p224r1_prod_redstep acc6,acc5,acc4,acc3,acc2
p224r1_prod_redstep acc7,acc6,acc5,acc4,acc3
mov acc0, acc4
mov acc1, acc5
mov acc2, acc6
mov acc3, acc7
sub acc4, qword ptr Lpoly+sizeof(qword)*0
sbb acc5, qword ptr Lpoly+sizeof(qword)*1
sbb acc6, qword ptr Lpoly+sizeof(qword)*2
sbb acc7, qword ptr Lpoly+sizeof(qword)*3
cmovc acc4, acc0
cmovc acc5, acc1
cmovc acc6, acc2
cmovc acc7, acc3
mov qword ptr[rdi+sizeof(qword)*0], acc4
mov qword ptr[rdi+sizeof(qword)*1], acc5
mov qword ptr[rdi+sizeof(qword)*2], acc6
mov qword ptr[rdi+sizeof(qword)*3], acc7
REST_XMM
REST_GPR
ret
IPPASM p224r1_mont_back ENDP
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p224r1_select_pp_w5(POINT *val, const POINT *in_t, int index);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ALIGN IPP_ALIGN_FACTOR
IPPASM p224r1_select_pp_w5 PROC PUBLIC FRAME
USES_GPR rsi,rdi,r12,r13
LOCAL_FRAME = 0
USES_XMM xmm6,xmm7,xmm8,xmm9,xmm10,xmm11,xmm12,xmm13,xmm14,xmm15
COMP_ABI 3
val equ rdi
in_t equ rsi
idx equ edx
ONE equ xmm0
INDEX equ xmm1
Ra equ xmm2
Rb equ xmm3
Rc equ xmm4
Rd equ xmm5
Re equ xmm6
Rf equ xmm7
M0 equ xmm8
T0a equ xmm9
T0b equ xmm10
T0c equ xmm11
T0d equ xmm12
T0e equ xmm13
T0f equ xmm14
TMP0 equ xmm15
movdqa ONE, oword ptr LOne
movdqa M0, ONE
movd INDEX, idx
pshufd INDEX, INDEX, 0
pxor Ra, Ra
pxor Rb, Rb
pxor Rc, Rc
pxor Rd, Rd
pxor Re, Re
pxor Rf, Rf
; Skip index = 0, is implicictly infty -> load with offset -1
mov rcx, 16
select_loop_sse_w5:
movdqa TMP0, M0
pcmpeqd TMP0, INDEX
paddd M0, ONE
movdqa T0a, oword ptr[in_t+sizeof(oword)*0]
movdqa T0b, oword ptr[in_t+sizeof(oword)*1]
movdqa T0c, oword ptr[in_t+sizeof(oword)*2]
movdqa T0d, oword ptr[in_t+sizeof(oword)*3]
movdqa T0e, oword ptr[in_t+sizeof(oword)*4]
movdqa T0f, oword ptr[in_t+sizeof(oword)*5]
add in_t, sizeof(oword)*6
pand T0a, TMP0
pand T0b, TMP0
pand T0c, TMP0
pand T0d, TMP0
pand T0e, TMP0
pand T0f, TMP0
por Ra, T0a
por Rb, T0b
por Rc, T0c
por Rd, T0d
por Re, T0e
por Rf, T0f
dec rcx
jnz select_loop_sse_w5
movdqu oword ptr[val+sizeof(oword)*0], Ra
movdqu oword ptr[val+sizeof(oword)*1], Rb
movdqu oword ptr[val+sizeof(oword)*2], Rc
movdqu oword ptr[val+sizeof(oword)*3], Rd
movdqu oword ptr[val+sizeof(oword)*4], Re
movdqu oword ptr[val+sizeof(oword)*5], Rf
REST_XMM
REST_GPR
ret
IPPASM p224r1_select_pp_w5 ENDP
IFNDEF _DISABLE_ECP_224R1_HARDCODED_BP_TBL_
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p224r1_select_ap_w7(AF_POINT *val, const AF_POINT *in_t, int index);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ALIGN IPP_ALIGN_FACTOR
IPPASM p224r1_select_ap_w7 PROC PUBLIC FRAME
USES_GPR rsi,rdi,r12,r13
LOCAL_FRAME = 0
USES_XMM xmm6,xmm7,xmm8,xmm9,xmm10,xmm11,xmm12,xmm13,xmm14,xmm15
COMP_ABI 3
val equ rdi
in_t equ rsi
idx equ edx
ONE equ xmm0
INDEX equ xmm1
Ra equ xmm2
Rb equ xmm3
Rc equ xmm4
Rd equ xmm5
M0 equ xmm8
T0a equ xmm9
T0b equ xmm10
T0c equ xmm11
T0d equ xmm12
TMP0 equ xmm15
movdqa ONE, oword ptr LOne
pxor Ra, Ra
pxor Rb, Rb
pxor Rc, Rc
pxor Rd, Rd
movdqa M0, ONE
movd INDEX, idx
pshufd INDEX, INDEX, 0
; Skip index = 0, is implicictly infty -> load with offset -1
mov rcx, 64
select_loop_sse_w7:
movdqa TMP0, M0
pcmpeqd TMP0, INDEX
paddd M0, ONE
movdqa T0a, oword ptr[in_t+sizeof(oword)*0]
movdqa T0b, oword ptr[in_t+sizeof(oword)*1]
movdqa T0c, oword ptr[in_t+sizeof(oword)*2]
movdqa T0d, oword ptr[in_t+sizeof(oword)*3]
add in_t, sizeof(oword)*4
pand T0a, TMP0
pand T0b, TMP0
pand T0c, TMP0
pand T0d, TMP0
por Ra, T0a
por Rb, T0b
por Rc, T0c
por Rd, T0d
dec rcx
jnz select_loop_sse_w7
movdqu oword ptr[val+sizeof(oword)*0], Ra
movdqu oword ptr[val+sizeof(oword)*1], Rb
movdqu oword ptr[val+sizeof(oword)*2], Rc
movdqu oword ptr[val+sizeof(oword)*3], Rd
REST_XMM
REST_GPR
ret
IPPASM p224r1_select_ap_w7 ENDP
ENDIF
ENDIF
END
|
// Copyright (c) 2017 Taeguk Kwon
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <pika/init.hpp>
#include <pika/modules/testing.hpp>
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include "remove_tests.hpp"
#include "test_utils.hpp"
////////////////////////////////////////////////////////////////////////////
void remove_test()
{
std::cout << "--- remove_test ---" << std::endl;
test_remove<std::bidirectional_iterator_tag>();
}
void remove_exception_test()
{
std::cout << "--- remove_exception_test ---" << std::endl;
test_remove_exception<std::bidirectional_iterator_tag>();
}
void remove_bad_alloc_test()
{
std::cout << "--- remove_bad_alloc_test ---" << std::endl;
test_remove_bad_alloc<std::bidirectional_iterator_tag>();
}
///////////////////////////////////////////////////////////////////////////////
int pika_main(pika::program_options::variables_map& vm)
{
unsigned int seed = (unsigned int) std::time(nullptr);
if (vm.count("seed"))
seed = vm["seed"].as<unsigned int>();
std::cout << "using seed: " << seed << std::endl;
std::srand(seed);
remove_test();
remove_exception_test();
remove_bad_alloc_test();
std::cout << "Test Finish!" << std::endl;
return pika::finalize();
}
int main(int argc, char* argv[])
{
// add command line option which controls the random number generator seed
using namespace pika::program_options;
options_description desc_commandline(
"Usage: " PIKA_APPLICATION_STRING " [options]");
desc_commandline.add_options()("seed,s", value<unsigned int>(),
"the random number generator seed to use for this run");
// By default this test should run on all available cores
std::vector<std::string> const cfg = {"pika.os_threads=all"};
// Initialize and run pika
pika::init_params init_args;
init_args.desc_cmdline = desc_commandline;
init_args.cfg = cfg;
PIKA_TEST_EQ_MSG(pika::init(pika_main, argc, argv, init_args), 0,
"pika main exited with non-zero status");
return pika::util::report_errors();
}
|
OPT r34 ; :3
OPT r 360
; Invalid
OPT r ; Missing arg
OPT r 2a ; Bad decimal
; Check that it has an effect
OPT r 1
MACRO m
m
ENDM
m
|
#include <fstream>
#include <math.h>
#include <uWS/uWS.h>
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
#include "Eigen-3.3/Eigen/Core"
#include "Eigen-3.3/Eigen/QR"
#include <iostream>
#include "map.h"
#include "vehicle.h"
#include "json.hpp"
#include "spline.h"
#include "Behaviour.h"
using namespace std;
// for convenience
using json = nlohmann::json;
// For converting back and forth between radians and degrees.
constexpr double pi() { return M_PI; }
double deg2rad(double x) { return x * pi() / 180; }
double rad2deg(double x) { return x * 180 / pi(); }
// Checks if the SocketIO event has JSON data.
// If there is data the JSON object in string format will be returned,
// else the empty string "" will be returned.
string hasData(string s) {
auto found_null = s.find("null");
auto b1 = s.find_first_of("[");
auto b2 = s.find_first_of("}");
if (found_null != string::npos) {
return "";
} else if (b1 != string::npos && b2 != string::npos) {
return s.substr(b1, b2 - b1 + 2);
}
return "";
}
int main() {
uWS::Hub h;
// Load up map values for waypoint's x,y,s and d normalized normal vectors
std::ofstream car_data;
std::ofstream sensor_data;
// for log file to save car & sensor data
car_data.open("../data/car_data.txt", ios::out);
sensor_data.open("../data/sensor_data.txt", ios::out);
car_data << "event_id,lane_id,car_id,x,y,speed,s,yaw\n";
sensor_data << "event_id,lane_id,car_id,x,y,speed,s,yaw\n";
// Waypoint map to read from
string map_file_ = "../data/highway_map.csv";
// The max s value before wrapping around the track back to 0
//double max_s = 6945.554;
// Map & Road & Vehicle & traject instances
Map map (map_file_);
Vehicle myCar;
Behariour behaivour;
// Car's lane. Starting at middle lane.
int lane = 1;
// Record EventId with Simulator to understand how many times called
int event_counter = 0;
// Reference velocity.
double REF_VEL = 0.0; // mph
//h.onMessage([&REF_VEL, &lane, &map_waypoints_x,&map_waypoints_y,&map_waypoints_s,&map_waypoints_dx,&map_waypoints_dy]
// (uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) {
h.onMessage([&REF_VEL, &lane, &map, &event_counter, &myCar, &behaivour]
(uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) {
// "42" at the start of the message means there's a websocket message event.
// The 4 signifies a websocket message
// The 2 signifies a websocket event
//auto sdata = string(data).substr(0, length);
//cout << sdata << endl;
if (length && length > 2 && data[0] == '4' && data[1] == '2') {
auto s = hasData(data);
if (s != "") {
auto j = json::parse(s);
string event = j[0].get<string>();
if (event == "telemetry") {
// j[1] is the data JSON object
// Main car's localization Data
double car_x = j[1]["x"];
double car_y = j[1]["y"];
double car_s = j[1]["s"];
double car_d = j[1]["d"];
double car_yaw = j[1]["yaw"];
double car_speed = j[1]["speed"];
// Previous path data given to the Planner
auto previous_path_x = j[1]["previous_path_x"];
auto previous_path_y = j[1]["previous_path_y"];
// Previous path's end s and d values
double end_path_s = j[1]["end_path_s"];
double end_path_d = j[1]["end_path_d"];
// Sensor Fusion Data, a list of all other cars on the same side of the road.
auto sensor_fusion = j[1]["sensor_fusion"];
// Provided previous path point size.
int prev_size = previous_path_x.size();
// Preventing collitions.
if (prev_size > 0) {
car_s = end_path_s;
}
event_counter += 1;
// myCar setup
myCar.setEventId(event_counter);
myCar.update_vehicle_values(car_x,car_y,car_speed,car_s,car_d,car_yaw);
myCar.set_previous_x(previous_path_x);
myCar.set_previous_y(previous_path_y);
// approach to solve best lane and speed_difference of accelaration
behaivour.setup(sensor_fusion, myCar, REF_VEL);
lane = behaivour.getlane();
// Behavior : Let's see what to do.
double speed_diff = behaivour.get_speed_diff();
vector<double> ptsx;
vector<double> ptsy;
double ref_x = car_x;
double ref_y = car_y;
double ref_yaw = deg2rad(car_yaw);
// Do I have have previous points
if ( prev_size < 2 ) {
// There are not too many...
double prev_car_x = car_x - cos(car_yaw);
double prev_car_y = car_y - sin(car_yaw);
ptsx.push_back(prev_car_x);
ptsx.push_back(car_x);
ptsy.push_back(prev_car_y);
ptsy.push_back(car_y);
} else {
// Use the last two points.
ref_x = previous_path_x[prev_size - 1];
ref_y = previous_path_y[prev_size - 1];
double ref_x_prev = previous_path_x[prev_size - 2];
double ref_y_prev = previous_path_y[prev_size - 2];
ref_yaw = atan2(ref_y-ref_y_prev, ref_x-ref_x_prev);
ptsx.push_back(ref_x_prev);
ptsx.push_back(ref_x);
ptsy.push_back(ref_y_prev);
ptsy.push_back(ref_y);
}
// use interpolate value from spline function with car_s + 30m 60m 90m
vector<double> next_wp0 = map.getXY(car_s + 30, 2 + 4*lane);
vector<double> next_wp1 = map.getXY(car_s + 60, 2 + 4*lane);
vector<double> next_wp2 = map.getXY(car_s + 90, 2 + 4*lane);
ptsx.push_back(next_wp0[0]);
ptsx.push_back(next_wp1[0]);
ptsx.push_back(next_wp2[0]);
ptsy.push_back(next_wp0[1]);
ptsy.push_back(next_wp1[1]);
ptsy.push_back(next_wp2[1]);
// Making coordinates to local car coordinates.
for ( int i = 0; i < ptsx.size(); i++ ) {
double shift_x = ptsx[i] - ref_x;
double shift_y = ptsy[i] - ref_y;
ptsx[i] = shift_x * cos(0 - ref_yaw) - shift_y * sin(0 - ref_yaw);
ptsy[i] = shift_x * sin(0 - ref_yaw) + shift_y * cos(0 - ref_yaw);
}
// Create the spline.
tk::spline s;
s.set_points(ptsx, ptsy);
// Output path points from previous path for continuity.
vector<double> next_x_vals;
vector<double> next_y_vals;
for ( int i = 0; i < prev_size; i++ ) {
next_x_vals.push_back(previous_path_x[i]);
next_y_vals.push_back(previous_path_y[i]);
}
// Calculate distance y position on 30 m ahead.
double target_x = 30.0;
double target_y = s(target_x);
double target_dist = sqrt(target_x*target_x + target_y*target_y);
double x_add_on = 0;
for( int i = 1; i < 50 - prev_size; i++ ) {
REF_VEL += speed_diff;
if ( REF_VEL > PARAM_MAX_SPEED_MPH ) {
REF_VEL = PARAM_MAX_SPEED_MPH;
} else if ( REF_VEL < MAX_ACC ) {
REF_VEL = MAX_ACC;
}
double N = target_dist/(0.02*REF_VEL/2.24);
double x_point = x_add_on + target_x/N;
double y_point = s(x_point);
x_add_on = x_point;
double x_ref = x_point;
double y_ref = y_point;
x_point = x_ref * cos(ref_yaw) - y_ref * sin(ref_yaw);
y_point = x_ref * sin(ref_yaw) + y_ref * cos(ref_yaw);
x_point += ref_x;
y_point += ref_y;
next_x_vals.push_back(x_point);
next_y_vals.push_back(y_point);
}
json msgJson;
msgJson["next_x"] = next_x_vals;
msgJson["next_y"] = next_y_vals;
auto msg = "42[\"control\","+ msgJson.dump()+"]";
//this_thread::sleep_for(chrono::milliseconds(1000));
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
} else {
// Manual driving
std::string msg = "42[\"manual\",{}]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
}
});
// We don't need this since we're not using HTTP but if it's removed the
// program
// doesn't compile :-(
h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data,
size_t, size_t) {
const std::string s = "<h1>Hello world!</h1>";
if (req.getUrl().valueLength == 1) {
res->end(s.data(), s.length());
} else {
// i guess this should be done more gracefully?
res->end(nullptr, 0);
}
});
h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {
std::cout << "Connected!!!" << std::endl;
});
h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code,
char *message, size_t length) {
ws.close();
std::cout << "Disconnected" << std::endl;
});
int port = 4567;
if (h.listen(port)) {
std::cout << "Listening to port " << port << std::endl;
} else {
std::cerr << "Failed to listen to port" << std::endl;
return -1;
}
h.run();
}
|
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <map>
#include <vector>
#include <list>
#include <filesystem>
namespace fs = std::filesystem;
#define GL_GLEXT_PROTOTYPES
#include <GL/gl.h>
#include <GL/glext.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "primitives.h"
using namespace glm;
static void error_callback(int error, const char *description)
{
fputs(description, stderr);
}
static void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
}
std::string loadFile(const std::string &path)
{
auto ss = std::ostringstream{};
std::ifstream file(path);
ss << file.rdbuf();
return ss.str();
}
GLuint compileShader(GLenum shaderType, std::string src) {
GLuint shader = glCreateShader(shaderType);
const char* vsc = src.c_str();
glShaderSource(shader, 1, &vsc, NULL);
glCompileShader(shader);
GLint result = GL_FALSE;
glGetShaderiv(shader, GL_COMPILE_STATUS, &result);
if( result != GL_TRUE ) {
//Note: maxLength includes the NUL terminator.
GLint maxLength = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
//C++11 does not permit you to overwrite the NUL terminator,
//even if you are overwriting it with the NUL terminator.
//C++17 does, so you could subtract 1 from the length and skip the `pop_back`.
std::basic_string<GLchar> infoLog(maxLength, '\0');
glGetShaderInfoLog(shader, maxLength, &maxLength, &infoLog[0]);
infoLog.pop_back();
//Use the infoLog in whatever manner you deem best.
throw std::runtime_error(
"Failed to compile shader: \n" +
src + "\n\n" +
infoLog + "\n");
}
return shader;
}
template<typename Iterable>
GLuint linkProgram(const Iterable& shaders) {
GLuint program = glCreateProgram();
for( const auto& s : shaders ) glAttachShader(program, s);
glLinkProgram(program);
GLint result = GL_FALSE;
glGetProgramiv(program, GL_LINK_STATUS, &result);
if( result != GL_TRUE ) {
//Note: maxLength includes the NUL terminator.
GLint maxLength = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength);
//C++11 does not permit you to overwrite the NUL terminator,
//even if you are overwriting it with the NUL terminator.
//C++17 does, so you could subtract 1 from the length and skip the `pop_back`.
std::basic_string<GLchar> infoLog(maxLength, '\0');
glGetProgramInfoLog(program, maxLength, &maxLength, &infoLog[0]);
infoLog.pop_back();
//Use the infoLog in whatever manner you deem best.
throw std::runtime_error("Failed to link shader: " + infoLog);
}
return program;
}
auto load_primitive_shaders(std::string primitiveDir) {
std::list<std::pair<std::string, std::string>> results;
for(auto& p: fs::directory_iterator(primitiveDir)) {
results.push_back(std::make_pair( p.path().stem(), loadFile(p.path() )));
}
return results;
}
std::string buildFragShader(std::string shaderDir, std::map<std::string, float>& typeMap) {
std::string fs_source = loadFile(shaderDir + "/raytrace_quad.frag");
const auto primitives = load_primitive_shaders(shaderDir + "/primitive_functions");
std::string all_prims;
for( auto& prim: primitives ) {
all_prims.append(prim.second);
all_prims.append("\n\n");
}
std::stringstream primInsert;
primInsert << R"(
// Default function definitions - Used if primitives aren't declared
bool is_null_type(int i) { return false; }
int calc_null_intersect(int i, Ray ray, out Intersection[2] intersections) { intersections[0].t = limit_inf; intersections[1].t = limit_inf; return 0; }
vec4 calc_null_normal(int i, vec4 p) { return vec4(0.0, 0.0, 0.0, 0.0); }
)";
auto i = 1u;
for( auto& prim: primitives ) {
primInsert << "bool is_" << prim.first << "(int i) { return primitives[i].meta.x == float(" << i << "); }\n";
++i;
}
i = 1u;
for( auto& prim: primitives ) {
primInsert <<
"#define PRIMITIVE_" << i << "_TYPE " << "is_" << prim.first << "\n" <<
"#define PRIMITIVE_" << i << "_INTERSECT " << prim.first << "_intersect" << "\n" <<
"#define PRIMITIVE_" << i << "_NORMAL " << prim.first << "_normal" << "\n";
++i;
}
primInsert << all_prims;
primInsert << "int calc_primitive_intersect(int i, Ray ray, out Intersection[2] intersections) {\n";
i = 1u;
for( auto& prim: primitives ) {
if( i == 1 )
primInsert << "if( PRIMITIVE_1_TYPE(i) ) return PRIMITIVE_1_INTERSECT(i, ray, intersections);\n";
else
primInsert << "else if( PRIMITIVE_" << i << "_TYPE(i) ) return PRIMITIVE_" << i << "_INTERSECT(i, ray, intersections);\n";
++i;
}
primInsert << "return calc_null_intersect(i, ray, intersections);\n}\n";
primInsert << "vec4 calc_primitive_normal(int i, vec4 p) {\n";
i = 1u;
for( auto& prim: primitives ) {
if( i == 1 )
primInsert << "if( PRIMITIVE_1_TYPE(i) ) return PRIMITIVE_1_NORMAL(i, p);\n";
else
primInsert << "else if( PRIMITIVE_" << i << "_TYPE(i) ) return PRIMITIVE_" << i << "_NORMAL(i, p);\n";
++i;
}
primInsert << "return calc_null_normal(i, p);\n}\n";
const std::string marker = "#primitivefunctions";
fs_source.replace(fs_source.find(marker), marker.size(), (const std::string&)primInsert.str());
i = 1u;
for( auto& prim: primitives ) {
typeMap[prim.first] = static_cast<float>(i);
++i;
}
return fs_source;
}
class Renderer
{
public:
bool initialised = false;
GLuint quad_program = 0;
GLuint quad_vao = 0;
GLuint quad_vbo = 0;
GLuint quad_vbo_uv = 0;
std::map<std::string, GLint> quad_program_uni;
GLuint primitives_ubo = 0;
glm::vec4 eyePos = {4.0, 6.0, 30.0, 1.0};
std::vector<Material> materials;
std::vector<PointLight> lights;
std::vector<Primitive> primitives;
uint32_t width, height;
glm::mat4 viewMatrix;
std::vector<float> viewParams;
Renderer(uint32_t w, uint32_t h)
: width(w), height(h)
{
viewMatrix = glm::mat4(1.0f);
init();
}
void init()
{
// The Scene
create_primitives();
// Shaders
const std::string vs_source = loadFile("../../shaders/raytrace_quad.vert");
std::map<std::string, float> typeMap;
auto fs_source = buildFragShader("../../shaders/", typeMap);
auto vs = compileShader(GL_VERTEX_SHADER, vs_source);
auto fs = compileShader(GL_FRAGMENT_SHADER, fs_source);
quad_program = linkProgram(std::list<GLuint>{vs, fs});
glUseProgram(quad_program);
glCreateVertexArrays(1, &quad_vao);
glBindVertexArray(quad_vao);
float positions[] = {
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0,
1.0, 1.0, 0.0,
1.0, 1.0, 0.0,
-1.0, 1.0, 0.0,
-1.0, -1.0, 0.0
};
glCreateBuffers(1, &quad_vbo);
glBindBuffer(GL_ARRAY_BUFFER, quad_vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(positions), positions, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);
glEnableVertexAttribArray(0);
float texCoords[] = {
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
1.0, 1.0,
0.0, 1.0,
0.0, 0.0
};
glCreateBuffers(1, &quad_vbo_uv);
glBindBuffer(GL_ARRAY_BUFFER, quad_vbo_uv);
glBufferData(GL_ARRAY_BUFFER, sizeof(texCoords), texCoords, GL_STATIC_DRAW);
glVertexAttribPointer(1, 2, GL_FLOAT, false, 0, 0);
glEnableVertexAttribArray(1);
// Uniform locations & buffers
quad_program_uni = {
{"viewParams", glGetUniformLocation(quad_program, "viewParams")},
{"viewMatrix", glGetUniformLocation(quad_program, "viewMatrix")},
{"iNumPrimitives", glGetUniformLocation(quad_program, "iNumPrimitives")},
{"iNumMaterials", glGetUniformLocation(quad_program, "iNumMaterials")},
{"iNumLights", glGetUniformLocation(quad_program, "iNumLights")},
{"ubo_0", glGetUniformBlockIndex(quad_program, "ubo_0")}
};
upload_ubo_0(quad_program_uni["ubo_0"], typeMap);
// Minor thing, but we don't need depth testing for full-screen ray tracing
// glDisable(GL_DEPTH_TEST);
initialised = true;
}
void create_primitives() {
auto m = Material();
glm::vec4 baseColour = {0.7,0.2,0.7,1.0};
m.ambient *= baseColour;
m.diffuse *= baseColour;
materials.push_back(m);
m = Material();
baseColour = {0.2,0.7,0.2,1.0};
m.ambient *= baseColour;
m.diffuse *= baseColour;
materials.push_back(m);
m = Material();
baseColour = {1.0, 1.0, 1.0, 1.0};
m.ambient *= baseColour;
m.diffuse *= baseColour;
materials.push_back(m);
m = Material();
baseColour = {0.9, 0.9, 0.9, 1.0};
m.ambient *= baseColour;
m.diffuse *= baseColour;
m.specular *= glm::vec4{0.2, 0.2, 0.2, 1.0};
m.specular[3] = 1.0;
materials.push_back(m);
m = Material();
baseColour = {0.9, 0.9, 0.9, 1.0};
m.ambient *= baseColour;
m.diffuse *= baseColour;
m.specular *= glm::vec4{0.2, 0.2, 0.2, 1.0};
m.specular[3] = 1.0;
m.reflectivity() = 0.5;
materials.push_back(m);
m = Material();
baseColour = {0.9, 0.9, 0.9, 1.0};
m.ambient *= baseColour;
m.diffuse *= baseColour;
m.specular *= glm::vec4{0.2, 0.2, 0.2, 1.0};
m.specular[3] = 1.0;
m.reflectivity() = 1.0;
materials.push_back(m);
m = Material();
baseColour = {1.0, 0.1, 0.1, 1.0};
m.ambient *= baseColour;
m.diffuse *= baseColour;
m.specular[3] = 8.0;
m.reflectivity() = 0.3;
materials.push_back(m);
m = Material();
baseColour = {0.1, 0.1, 1.0, 1.0};
m.ambient *= baseColour;
m.diffuse *= baseColour;
m.specular[3] = 16.0;
m.transparency() = 0.7;
materials.push_back(m);
/////////////
auto l = PointLight();
l.position = { 0.0, 20.0, 20.0, 1.0 };
l.intensity = {0.3, 0.3, 0.3, 1.0 };
l.cast_shadows = true;
lights.push_back(l);
l = PointLight();
l.position = {-30.0, 20.0, 30.0, 1.0 };
l.cast_shadows = false;
lights.push_back(l);
l = PointLight();
l.position = {20.0, 10.0, 0.0, 1.0 };
l.cast_shadows = false;
lights.push_back(l);
/////////////
// bigboi
Primitive p = Sphere();
p.material() = 5;
p.modelMatrix = glm::translate(p.modelMatrix, {-3, 2, 0});
p.modelMatrix = glm::scale(p.modelMatrix, {2,2,2});
primitives.push_back(p);
// transparentboi
p = Sphere();
p.material() = 6;
p.modelMatrix = glm::translate(p.modelMatrix, {0, 2, 5});
p.modelMatrix = glm::scale(p.modelMatrix, {4,4,4});
primitives.push_back(p);
p = Sphere();
p.material() = 7;
p.modelMatrix = glm::translate(p.modelMatrix, {0, 2, -10});
p.modelMatrix = glm::scale(p.modelMatrix, {16, 4, 16});
primitives.push_back(p);
// hugeboi
p = Sphere();
p.material() = 1;
p.modelMatrix = glm::translate(p.modelMatrix, {0, -9, 0});
p.modelMatrix = glm::scale(p.modelMatrix, {10,10,10});
p.pattern_type() = 1;
p.pattern = {64, 0, 0, 0};
primitives.push_back(p);
// smolboi
p = Sphere();
p.material() = 0;
p.modelMatrix = glm::translate(p.modelMatrix, {1,2,0});
p.modelMatrix = glm::scale(p.modelMatrix, {0.5,0.5,0.5});
primitives.push_back(p);
// The room, 50x50x50
glm::vec4 xwall_pattern = { 1.0, 16.0, 0.0, 0.0 };
glm::vec4 zwall_pattern = { 8.0, 8.0, 0.0, 0.0 };
// floor and ceiling
p = PlaneXZ();
p.material() = 4;
primitives.push_back(p);
// x walls
p = PlaneXZ();
p.material() = 5;
p.modelMatrix = glm::translate(p.modelMatrix, {60,0,0});
p.modelMatrix = glm::rotate(p.modelMatrix, glm::radians(130.0f), glm::vec3{0.0f,0.0f,1.0f});
primitives.push_back(p);
p = PlaneXZ();
p.material() = 5;
p.modelMatrix = glm::translate(p.modelMatrix, {-60,0,0});
p.modelMatrix = glm::rotate(p.modelMatrix, glm::radians(-130.0f), glm::vec3{0.0f,0.0f,1.0f});
primitives.push_back(p);
// z walls
p = PlaneXZ();
p.material() = 5;
p.modelMatrix = glm::translate(p.modelMatrix, {0.0, 0.0, 60.0});
p.modelMatrix = glm::rotate(p.modelMatrix, glm::radians(-130.0f), glm::vec3{1.0f, 0.0f, 0.0f});
primitives.push_back(p);
p = PlaneXZ();
p.material() = 5;
p.modelMatrix = glm::translate(p.modelMatrix, {0.0, 0.0, -60.0});
p.modelMatrix = glm::rotate(p.modelMatrix, glm::radians(130.0f), glm::vec3{1.0f, 0.0f, 0.0f});
primitives.push_back(p);
// A translucent plane, splitting the middle of smolboi and bigboi
// p = PlaneXZ();
// p.material() = 6;
// p.modelMatrix = glm::rotate(p.modelMatrix, glm::radians(90.0f), glm::vec3{1.0f, 0.0f, 0.0f});
// primitives.push_back(p);
}
void upload_ubo_0(GLint ubo_index, std::map<std::string, float> typeMap ) {
// Get the buffer size + offsets
GLint ubo_size = 0;
glGetActiveUniformBlockiv(quad_program, ubo_index, GL_UNIFORM_BLOCK_DATA_SIZE, &ubo_size);
float data[ubo_size / sizeof(float)];
// Size and offsets in floats
// The structure padding is excessive/paranoid here, but allows for future expansion
const uint32_t light_size = 16;
const uint32_t material_size = 16;
const uint32_t primitive_size = 32;
// MAKE SURE THESE MATCH THE SHADER!
const uint32_t max_lights = 4;
const uint32_t max_materials = 8;
const uint32_t max_primitives = 20;
const uint32_t lights_offset = 0;
const uint32_t materials_offset = max_lights * light_size;
const uint32_t primitives_offset = materials_offset + (max_materials * material_size);
auto num_lights = lights.size();
if (num_lights > max_lights)
{
throw std::runtime_error("Too many lights");
num_lights = max_lights;
}
auto num_materials = materials.size();
if (num_lights > max_lights)
{
throw std::runtime_error("Too many materials");
num_lights = max_lights;
}
auto num_primitives = primitives.size();
if (num_lights > max_lights)
{
throw std::runtime_error("Too many primitives");
num_lights = max_lights;
}
for (auto i = 0; i < num_lights; i++)
{
auto offset = lights_offset + (i * light_size);
auto& l = lights[i];
data[offset++] = l.intensity[0];
data[offset++] = l.intensity[1];
data[offset++] = l.intensity[2];
data[offset++] = l.intensity[3];
data[offset++] = l.position[0];
data[offset++] = l.position[1];
data[offset++] = l.position[2];
data[offset++] = l.position[3];
if (l.cast_shadows)
{
data[offset++] = 1.0;
}
else
{
data[offset++] = 0.0;
}
}
for (auto i = 0; i < num_materials; i++)
{
auto offset = materials_offset + (i * material_size);
auto& m = materials[i];
data[offset++] = m.ambient[0];
data[offset++] = m.ambient[1];
data[offset++] = m.ambient[2];
data[offset++] = m.ambient[3];
data[offset++] = m.diffuse[0];
data[offset++] = m.diffuse[1];
data[offset++] = m.diffuse[2];
data[offset++] = m.diffuse[3];
data[offset++] = m.specular[0];
data[offset++] = m.specular[1];
data[offset++] = m.specular[2];
data[offset++] = m.specular[3];
data[offset++] = m.phys[0];
data[offset++] = m.phys[1];
data[offset++] = m.phys[2];
data[offset++] = m.phys[3];
}
for (auto i = 0; i < num_primitives; i++)
{
auto offset = primitives_offset + (i * primitive_size);
auto& p = primitives[i];
p.type_number() = typeMap[p.type];
data[offset++] = p.modelMatrix[0][0];
data[offset++] = p.modelMatrix[0][1];
data[offset++] = p.modelMatrix[0][2];
data[offset++] = p.modelMatrix[0][3];
data[offset++] = p.modelMatrix[1][0];
data[offset++] = p.modelMatrix[1][1];
data[offset++] = p.modelMatrix[1][2];
data[offset++] = p.modelMatrix[1][3];
data[offset++] = p.modelMatrix[2][0];
data[offset++] = p.modelMatrix[2][1];
data[offset++] = p.modelMatrix[2][2];
data[offset++] = p.modelMatrix[2][3];
data[offset++] = p.modelMatrix[3][0];
data[offset++] = p.modelMatrix[3][1];
data[offset++] = p.modelMatrix[3][2];
data[offset++] = p.modelMatrix[3][3];
data[offset++] = p.meta[0];
data[offset++] = p.meta[1];
data[offset++] = p.meta[2];
data[offset++] = p.meta[3];
data[offset++] = p.pattern[0];
data[offset++] = p.pattern[1];
data[offset++] = p.pattern[2];
data[offset++] = p.pattern[3];
}
glCreateBuffers(1, &primitives_ubo);
glBindBuffer(GL_UNIFORM_BUFFER, primitives_ubo);
glBindBufferBase(GL_UNIFORM_BUFFER, 0, primitives_ubo);
glBufferData(GL_UNIFORM_BUFFER, sizeof(data), data, GL_DYNAMIC_DRAW);
// std::exit(1);
}
void render() {
if (!initialised)
{
return;
}
// Perspective parameters
// TODO: This is calculated within the shader, there is no projection matrix
float fov = 60.0;
float nearZ = 1.0;
float farZ = 100.0;
viewParams = {(float)width, (float)height, glm::radians(fov), nearZ};
float eyeRot = 0.005;
glm::mat4 rotMat(1.0f);
rotMat = glm::rotate(rotMat, eyeRot, {0.f,1.f,0.f});
eyePos = rotMat * eyePos;
viewMatrix = glm::lookAt(glm::vec3{eyePos.x,eyePos.y,eyePos.z}, glm::vec3{0.0, 0.0, 0.0}, glm::vec3{0.0, 1.0, 0.0});
glViewport(0, 0, width, height);
// Set clear color to black, fully opaque
glClearColor(0.0, 0.0, 0.0, 1.0);
// Clear the color buffer with specified clear color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Draw the ray traced stuff
glUseProgram(quad_program);
glBindVertexArray(quad_vao);
glUniformBlockBinding(quad_program, quad_program_uni["primitives_ubo"], 0);
glBindBufferBase(GL_UNIFORM_BUFFER, 0, primitives_ubo);
update_uniforms();
glDrawArrays(GL_TRIANGLES, 0, 6);
}
void update_uniforms()
{
glUniform4f(quad_program_uni["viewParams"],
viewParams[0],
viewParams[1],
viewParams[2],
viewParams[3]
);
glUniform1i(quad_program_uni["iNumPrimitives"], primitives.size());
glUniform1i(quad_program_uni["iNumMaterials"], materials.size());
glUniform1i(quad_program_uni["iNumLights"], lights.size());
glUniformMatrix4fv(quad_program_uni["viewMatrix"], 1, GL_FALSE, glm::value_ptr(viewMatrix));
}
};
void APIENTRY glDebugOutput(GLenum source,
GLenum type,
unsigned int id,
GLenum severity,
GLsizei length,
const char *message,
const void *userParam)
{
// ignore non-significant error/warning codes
if(id == 131169 || id == 131185 || id == 131218 || id == 131204) return;
std::cout << "---------------" << std::endl;
std::cout << "Debug message (" << id << "): " << message << std::endl;
switch (source)
{
case GL_DEBUG_SOURCE_API: std::cout << "Source: API"; break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM: std::cout << "Source: Window System"; break;
case GL_DEBUG_SOURCE_SHADER_COMPILER: std::cout << "Source: Shader Compiler"; break;
case GL_DEBUG_SOURCE_THIRD_PARTY: std::cout << "Source: Third Party"; break;
case GL_DEBUG_SOURCE_APPLICATION: std::cout << "Source: Application"; break;
case GL_DEBUG_SOURCE_OTHER: std::cout << "Source: Other"; break;
} std::cout << std::endl;
switch (type)
{
case GL_DEBUG_TYPE_ERROR: std::cout << "Type: Error"; break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: std::cout << "Type: Deprecated Behaviour"; break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: std::cout << "Type: Undefined Behaviour"; break;
case GL_DEBUG_TYPE_PORTABILITY: std::cout << "Type: Portability"; break;
case GL_DEBUG_TYPE_PERFORMANCE: std::cout << "Type: Performance"; break;
case GL_DEBUG_TYPE_MARKER: std::cout << "Type: Marker"; break;
case GL_DEBUG_TYPE_PUSH_GROUP: std::cout << "Type: Push Group"; break;
case GL_DEBUG_TYPE_POP_GROUP: std::cout << "Type: Pop Group"; break;
case GL_DEBUG_TYPE_OTHER: std::cout << "Type: Other"; break;
} std::cout << std::endl;
switch (severity)
{
case GL_DEBUG_SEVERITY_HIGH: std::cout << "Severity: high"; break;
case GL_DEBUG_SEVERITY_MEDIUM: std::cout << "Severity: medium"; break;
case GL_DEBUG_SEVERITY_LOW: std::cout << "Severity: low"; break;
case GL_DEBUG_SEVERITY_NOTIFICATION: std::cout << "Severity: notification"; break;
} std::cout << std::endl;
std::cout << std::endl;
}
int main(void)
{
GLFWwindow *window;
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, true);
auto w = 800;
auto h = 800;
window = glfwCreateWindow(w, h, "Web Tracing CeePlusPlus", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
int flags; glGetIntegerv(GL_CONTEXT_FLAGS, &flags);
if (flags & GL_CONTEXT_FLAG_DEBUG_BIT)
{
glEnable(GL_DEBUG_OUTPUT);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback(glDebugOutput, nullptr);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE);
}
glfwSetKeyCallback(window, key_callback);
// glfwSwapInterval(1);
Renderer renderer(w, h);
while (!glfwWindowShouldClose(window))
{
renderer.render();
glfwSwapBuffers(window);
glfwPollEvents();
//glfwWaitEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
|
copyright zengfr site:http://github.com/zengfr/romhack
0047B4 move.w D0, D2 [enemy+A5]
02522C move.b #$f, ($a5,A0) [enemy+AE]
025232 addq.b #2, ($29,A0) [enemy+A5]
copyright zengfr site:http://github.com/zengfr/romhack
|
; Copyright (c) 2004, Intel Corporation. All rights reserved.<BR>
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution. The full text of the license may be found at
; http://opensource.org/licenses/bsd-license.php
;
; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
;
; Module Name:
;
; SwitchStack.Asm
;
; Abstract:
;
;------------------------------------------------------------------------------
.code
;------------------------------------------------------------------------------
; Routine Description:
;
; Routine for switching stacks with 1 parameter
;
; Arguments:
;
; (rcx) EntryPoint - Entry point with new stack.
; (rdx) Context - Parameter for entry point.
; (r8) Context2 - Parameter2 for entry point.
; (r9) NewStack - Pointer to new stack.
;
; Returns:
;
; None
;
;------------------------------------------------------------------------------
InternalSwitchStack PROC
mov rax, rcx
mov rcx, rdx
mov rdx, r8
lea rsp, [r9 - 20h]
call rax
InternalSwitchStack ENDP
END
|
; Map 19 init
lda #$58
sta Timer1
lda #$04
sta Timer2
rts
|
; A248178: Least k such that r - sum{1/F(n), h = 1..k} < 1/2^(n+1), where F(n) = A000045 (Fibonacci numbers) and r = sum{1/F(n), h = 1..infinity}.
; 6,7,9,10,12,13,15,16,18,19,20,22,23,25,26,28,29,31,32,33,35,36,38,39,41,42,44,45,46,48,49,51,52,54,55,56,58,59,61,62,64,65,67,68,69,71,72,74,75,77,78,80,81,82,84,85,87,88,90,91,92,94,95,97,98,100,101,103,104,105,107,108,110,111,113,114,116,117,118,120,121,123,124,126,127,128,130,131,133,134,136,137,139,140,141,143,144,146,147,149
mov $2,$0
mov $3,$0
mov $4,$0
mul $0,2
mov $1,1
sub $4,3
sub $1,$4
sub $1,$0
div $1,25
add $1,$3
div $1,2
add $1,6
add $1,$2
mov $0,$1
|
/*
* Copyright 2004 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/base/unixfilesystem.h"
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
#include <Carbon/Carbon.h>
#include <IOKit/IOCFBundle.h>
#include <sys/statvfs.h>
#include "webrtc/base/macutils.h"
#endif // WEBRTC_MAC && !defined(WEBRTC_IOS)
#if defined(WEBRTC_POSIX) && !defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
#include <sys/types.h>
#if defined(WEBRTC_ANDROID)
#include <sys/statfs.h>
#elif !defined(__native_client__)
#include <sys/statvfs.h>
#endif // !defined(__native_client__)
#include <limits.h>
#include <pwd.h>
#include <stdio.h>
#endif // WEBRTC_POSIX && !WEBRTC_MAC || WEBRTC_IOS
#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
#include <ctype.h>
#include <algorithm>
#endif
#if defined(__native_client__) && !defined(__GLIBC__)
#include <sys/syslimits.h>
#endif
#include "webrtc/base/fileutils.h"
#include "webrtc/base/pathutils.h"
#include "webrtc/base/stream.h"
#include "webrtc/base/stringutils.h"
#if defined(WEBRTC_IOS)
// Defined in iosfilesystem.mm. No header file to discourage use
// elsewhere; other places should use GetApp{Data,Temp}Folder() in
// this file. Don't copy/paste. I mean it.
char* IOSDataDirectory();
char* IOSTempDirectory();
void IOSAppName(rtc::Pathname* path);
#endif
namespace rtc {
#if !defined(WEBRTC_ANDROID) && !defined(WEBRTC_IOS)
char* UnixFilesystem::app_temp_path_ = NULL;
#else
char* UnixFilesystem::provided_app_data_folder_ = NULL;
char* UnixFilesystem::provided_app_temp_folder_ = NULL;
void UnixFilesystem::SetAppDataFolder(const std::string& folder) {
delete [] provided_app_data_folder_;
provided_app_data_folder_ = CopyString(folder);
}
void UnixFilesystem::SetAppTempFolder(const std::string& folder) {
delete [] provided_app_temp_folder_;
provided_app_temp_folder_ = CopyString(folder);
}
#endif
UnixFilesystem::UnixFilesystem() {
#if defined(WEBRTC_IOS)
if (!provided_app_data_folder_)
provided_app_data_folder_ = IOSDataDirectory();
if (!provided_app_temp_folder_)
provided_app_temp_folder_ = IOSTempDirectory();
#endif
}
UnixFilesystem::~UnixFilesystem() {}
bool UnixFilesystem::CreateFolder(const Pathname &path, mode_t mode) {
std::string pathname(path.pathname());
int len = pathname.length();
if ((len == 0) || (pathname[len - 1] != '/'))
return false;
struct stat st;
int res = ::stat(pathname.c_str(), &st);
if (res == 0) {
// Something exists at this location, check if it is a directory
return S_ISDIR(st.st_mode) != 0;
} else if (errno != ENOENT) {
// Unexpected error
return false;
}
// Directory doesn't exist, look up one directory level
do {
--len;
} while ((len > 0) && (pathname[len - 1] != '/'));
if (!CreateFolder(Pathname(pathname.substr(0, len)), mode)) {
return false;
}
LOG(LS_INFO) << "Creating folder: " << pathname;
return (0 == ::mkdir(pathname.c_str(), mode));
}
bool UnixFilesystem::CreateFolder(const Pathname &path) {
return CreateFolder(path, 0755);
}
FileStream *UnixFilesystem::OpenFile(const Pathname &filename,
const std::string &mode) {
FileStream *fs = new FileStream();
if (fs && !fs->Open(filename.pathname().c_str(), mode.c_str(), NULL)) {
delete fs;
fs = NULL;
}
return fs;
}
bool UnixFilesystem::CreatePrivateFile(const Pathname &filename) {
int fd = open(filename.pathname().c_str(),
O_RDWR | O_CREAT | O_EXCL,
S_IRUSR | S_IWUSR);
if (fd < 0) {
LOG_ERR(LS_ERROR) << "open() failed.";
return false;
}
// Don't need to keep the file descriptor.
if (close(fd) < 0) {
LOG_ERR(LS_ERROR) << "close() failed.";
// Continue.
}
return true;
}
bool UnixFilesystem::DeleteFile(const Pathname &filename) {
LOG(LS_INFO) << "Deleting file:" << filename.pathname();
if (!IsFile(filename)) {
ASSERT(IsFile(filename));
return false;
}
return ::unlink(filename.pathname().c_str()) == 0;
}
bool UnixFilesystem::DeleteEmptyFolder(const Pathname &folder) {
LOG(LS_INFO) << "Deleting folder" << folder.pathname();
if (!IsFolder(folder)) {
ASSERT(IsFolder(folder));
return false;
}
std::string no_slash(folder.pathname(), 0, folder.pathname().length()-1);
return ::rmdir(no_slash.c_str()) == 0;
}
bool UnixFilesystem::GetTemporaryFolder(Pathname &pathname, bool create,
const std::string *append) {
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
FSRef fr;
if (0 != FSFindFolder(kOnAppropriateDisk, kTemporaryFolderType,
kCreateFolder, &fr))
return false;
unsigned char buffer[NAME_MAX+1];
if (0 != FSRefMakePath(&fr, buffer, ARRAY_SIZE(buffer)))
return false;
pathname.SetPathname(reinterpret_cast<char*>(buffer), "");
#elif defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
ASSERT(provided_app_temp_folder_ != NULL);
pathname.SetPathname(provided_app_temp_folder_, "");
#else // !WEBRTC_MAC || WEBRTC_IOS && !WEBRTC_ANDROID
if (const char* tmpdir = getenv("TMPDIR")) {
pathname.SetPathname(tmpdir, "");
} else if (const char* tmp = getenv("TMP")) {
pathname.SetPathname(tmp, "");
} else {
#ifdef P_tmpdir
pathname.SetPathname(P_tmpdir, "");
#else // !P_tmpdir
pathname.SetPathname("/tmp/", "");
#endif // !P_tmpdir
}
#endif // !WEBRTC_MAC || WEBRTC_IOS && !WEBRTC_ANDROID
if (append) {
ASSERT(!append->empty());
pathname.AppendFolder(*append);
}
return !create || CreateFolder(pathname);
}
std::string UnixFilesystem::TempFilename(const Pathname &dir,
const std::string &prefix) {
int len = dir.pathname().size() + prefix.size() + 2 + 6;
char *tempname = new char[len];
snprintf(tempname, len, "%s/%sXXXXXX", dir.pathname().c_str(),
prefix.c_str());
int fd = ::mkstemp(tempname);
if (fd != -1)
::close(fd);
std::string ret(tempname);
delete[] tempname;
return ret;
}
bool UnixFilesystem::MoveFile(const Pathname &old_path,
const Pathname &new_path) {
if (!IsFile(old_path)) {
ASSERT(IsFile(old_path));
return false;
}
LOG(LS_VERBOSE) << "Moving " << old_path.pathname()
<< " to " << new_path.pathname();
if (rename(old_path.pathname().c_str(), new_path.pathname().c_str()) != 0) {
if (errno != EXDEV)
return false;
if (!CopyFile(old_path, new_path))
return false;
if (!DeleteFile(old_path))
return false;
}
return true;
}
bool UnixFilesystem::MoveFolder(const Pathname &old_path,
const Pathname &new_path) {
if (!IsFolder(old_path)) {
ASSERT(IsFolder(old_path));
return false;
}
LOG(LS_VERBOSE) << "Moving " << old_path.pathname()
<< " to " << new_path.pathname();
if (rename(old_path.pathname().c_str(), new_path.pathname().c_str()) != 0) {
if (errno != EXDEV)
return false;
if (!CopyFolder(old_path, new_path))
return false;
if (!DeleteFolderAndContents(old_path))
return false;
}
return true;
}
bool UnixFilesystem::IsFolder(const Pathname &path) {
struct stat st;
if (stat(path.pathname().c_str(), &st) < 0)
return false;
return S_ISDIR(st.st_mode);
}
bool UnixFilesystem::CopyFile(const Pathname &old_path,
const Pathname &new_path) {
LOG(LS_VERBOSE) << "Copying " << old_path.pathname()
<< " to " << new_path.pathname();
char buf[256];
size_t len;
StreamInterface *source = OpenFile(old_path, "rb");
if (!source)
return false;
StreamInterface *dest = OpenFile(new_path, "wb");
if (!dest) {
delete source;
return false;
}
while (source->Read(buf, sizeof(buf), &len, NULL) == SR_SUCCESS)
dest->Write(buf, len, NULL, NULL);
delete source;
delete dest;
return true;
}
bool UnixFilesystem::IsTemporaryPath(const Pathname& pathname) {
#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
ASSERT(provided_app_temp_folder_ != NULL);
#endif
const char* const kTempPrefixes[] = {
#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
provided_app_temp_folder_,
#else
"/tmp/", "/var/tmp/",
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
"/private/tmp/", "/private/var/tmp/", "/private/var/folders/",
#endif // WEBRTC_MAC && !defined(WEBRTC_IOS)
#endif // WEBRTC_ANDROID || WEBRTC_IOS
};
for (size_t i = 0; i < ARRAY_SIZE(kTempPrefixes); ++i) {
if (0 == strncmp(pathname.pathname().c_str(), kTempPrefixes[i],
strlen(kTempPrefixes[i])))
return true;
}
return false;
}
bool UnixFilesystem::IsFile(const Pathname& pathname) {
struct stat st;
int res = ::stat(pathname.pathname().c_str(), &st);
// Treat symlinks, named pipes, etc. all as files.
return res == 0 && !S_ISDIR(st.st_mode);
}
bool UnixFilesystem::IsAbsent(const Pathname& pathname) {
struct stat st;
int res = ::stat(pathname.pathname().c_str(), &st);
// Note: we specifically maintain ENOTDIR as an error, because that implies
// that you could not call CreateFolder(pathname).
return res != 0 && ENOENT == errno;
}
bool UnixFilesystem::GetFileSize(const Pathname& pathname, size_t *size) {
struct stat st;
if (::stat(pathname.pathname().c_str(), &st) != 0)
return false;
*size = st.st_size;
return true;
}
bool UnixFilesystem::GetFileTime(const Pathname& path, FileTimeType which,
time_t* time) {
struct stat st;
if (::stat(path.pathname().c_str(), &st) != 0)
return false;
switch (which) {
case FTT_CREATED:
*time = st.st_ctime;
break;
case FTT_MODIFIED:
*time = st.st_mtime;
break;
case FTT_ACCESSED:
*time = st.st_atime;
break;
default:
return false;
}
return true;
}
bool UnixFilesystem::GetAppPathname(Pathname* path) {
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
ProcessSerialNumber psn = { 0, kCurrentProcess };
CFDictionaryRef procinfo = ProcessInformationCopyDictionary(&psn,
kProcessDictionaryIncludeAllInformationMask);
if (NULL == procinfo)
return false;
CFStringRef cfpath = (CFStringRef) CFDictionaryGetValue(procinfo,
kIOBundleExecutableKey);
std::string path8;
bool success = ToUtf8(cfpath, &path8);
CFRelease(procinfo);
if (success)
path->SetPathname(path8);
return success;
#elif defined(__native_client__)
return false;
#elif IOS
IOSAppName(path);
return true;
#else // WEBRTC_MAC && !defined(WEBRTC_IOS)
char buffer[PATH_MAX + 2];
ssize_t len = readlink("/proc/self/exe", buffer, ARRAY_SIZE(buffer) - 1);
if ((len <= 0) || (len == PATH_MAX + 1))
return false;
buffer[len] = '\0';
path->SetPathname(buffer);
return true;
#endif // WEBRTC_MAC && !defined(WEBRTC_IOS)
}
bool UnixFilesystem::GetAppDataFolder(Pathname* path, bool per_user) {
ASSERT(!organization_name_.empty());
ASSERT(!application_name_.empty());
// First get the base directory for app data.
#if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS)
if (per_user) {
// Use ~/Library/Application Support/<orgname>/<appname>/
FSRef fr;
if (0 != FSFindFolder(kUserDomain, kApplicationSupportFolderType,
kCreateFolder, &fr))
return false;
unsigned char buffer[NAME_MAX+1];
if (0 != FSRefMakePath(&fr, buffer, ARRAY_SIZE(buffer)))
return false;
path->SetPathname(reinterpret_cast<char*>(buffer), "");
} else {
// TODO
return false;
}
#elif defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS) // && !WEBRTC_MAC || WEBRTC_IOS
ASSERT(provided_app_data_folder_ != NULL);
path->SetPathname(provided_app_data_folder_, "");
#elif defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID) // && !WEBRTC_MAC && !WEBRTC_IOS && !WEBRTC_ANDROID
if (per_user) {
// We follow the recommendations in
// http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
// It specifies separate directories for data and config files, but
// GetAppDataFolder() does not distinguish. We just return the config dir
// path.
const char* xdg_config_home = getenv("XDG_CONFIG_HOME");
if (xdg_config_home) {
path->SetPathname(xdg_config_home, "");
} else {
// XDG says to default to $HOME/.config. We also support falling back to
// other synonyms for HOME if for some reason it is not defined.
const char* homedir;
if (const char* home = getenv("HOME")) {
homedir = home;
} else if (const char* dotdir = getenv("DOTDIR")) {
homedir = dotdir;
} else if (passwd* pw = getpwuid(geteuid())) {
homedir = pw->pw_dir;
} else {
return false;
}
path->SetPathname(homedir, "");
path->AppendFolder(".config");
}
} else {
// XDG does not define a standard directory for writable global data. Let's
// just use this.
path->SetPathname("/var/cache/", "");
}
#endif // !WEBRTC_MAC && !WEBRTC_LINUX
// Now add on a sub-path for our app.
#if defined(WEBRTC_MAC) || defined(WEBRTC_ANDROID)
path->AppendFolder(organization_name_);
path->AppendFolder(application_name_);
#elif defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
// XDG says to use a single directory level, so we concatenate the org and app
// name with a hyphen. We also do the Linuxy thing and convert to all
// lowercase with no spaces.
std::string subdir(organization_name_);
subdir.append("-");
subdir.append(application_name_);
replace_substrs(" ", 1, "", 0, &subdir);
std::transform(subdir.begin(), subdir.end(), subdir.begin(), ::tolower);
path->AppendFolder(subdir);
#endif
if (!CreateFolder(*path, 0700)) {
return false;
}
#if !defined(__native_client__)
// If the folder already exists, it may have the wrong mode or be owned by
// someone else, both of which are security problems. Setting the mode
// avoids both issues since it will fail if the path is not owned by us.
if (0 != ::chmod(path->pathname().c_str(), 0700)) {
LOG_ERR(LS_ERROR) << "Can't set mode on " << path;
return false;
}
#endif
return true;
}
bool UnixFilesystem::GetAppTempFolder(Pathname* path) {
#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
ASSERT(provided_app_temp_folder_ != NULL);
path->SetPathname(provided_app_temp_folder_);
return true;
#else
ASSERT(!application_name_.empty());
// TODO: Consider whether we are worried about thread safety.
if (app_temp_path_ != NULL && strlen(app_temp_path_) > 0) {
path->SetPathname(app_temp_path_);
return true;
}
// Create a random directory as /tmp/<appname>-<pid>-<timestamp>
char buffer[128];
sprintfn(buffer, ARRAY_SIZE(buffer), "-%d-%d",
static_cast<int>(getpid()),
static_cast<int>(time(0)));
std::string folder(application_name_);
folder.append(buffer);
if (!GetTemporaryFolder(*path, true, &folder))
return false;
delete [] app_temp_path_;
app_temp_path_ = CopyString(path->pathname());
// TODO: atexit(DeleteFolderAndContents(app_temp_path_));
return true;
#endif
}
bool UnixFilesystem::GetDiskFreeSpace(const Pathname& path, int64 *freebytes) {
#ifdef __native_client__
return false;
#else // __native_client__
ASSERT(NULL != freebytes);
// TODO: Consider making relative paths absolute using cwd.
// TODO: When popping off a symlink, push back on the components of the
// symlink, so we don't jump out of the target disk inadvertently.
Pathname existing_path(path.folder(), "");
while (!existing_path.folder().empty() && IsAbsent(existing_path)) {
existing_path.SetFolder(existing_path.parent_folder());
}
#if defined(WEBRTC_ANDROID)
struct statfs vfs;
memset(&vfs, 0, sizeof(vfs));
if (0 != statfs(existing_path.pathname().c_str(), &vfs))
return false;
#else
struct statvfs vfs;
memset(&vfs, 0, sizeof(vfs));
if (0 != statvfs(existing_path.pathname().c_str(), &vfs))
return false;
#endif // WEBRTC_ANDROID
#if defined(WEBRTC_LINUX)
*freebytes = static_cast<int64>(vfs.f_bsize) * vfs.f_bavail;
#elif defined(WEBRTC_MAC)
*freebytes = static_cast<int64>(vfs.f_frsize) * vfs.f_bavail;
#endif
return true;
#endif // !__native_client__
}
Pathname UnixFilesystem::GetCurrentDirectory() {
Pathname cwd;
char buffer[PATH_MAX];
char *path = getcwd(buffer, PATH_MAX);
if (!path) {
LOG_ERR(LS_ERROR) << "getcwd() failed";
return cwd; // returns empty pathname
}
cwd.SetFolder(std::string(path));
return cwd;
}
char* UnixFilesystem::CopyString(const std::string& str) {
size_t size = str.length() + 1;
char* buf = new char[size];
if (!buf) {
return NULL;
}
strcpyn(buf, size, str.c_str());
return buf;
}
} // namespace rtc
#if defined(__native_client__)
extern "C" int __attribute__((weak))
link(const char* oldpath, const char* newpath) {
errno = EACCES;
return -1;
}
#endif
|
TITLE MISC2 - Miscellanious routines for MS-DOS
NAME MISC2
;** MISC2.ASM - Miscellaneous useful routines
;
; StrCpy
; StrCmp
; StrLen
; DStrLen
; Idle
; TableDispatch
; FastInit ; DOS 4.0
; FastRet ; DOS 4.0
; NLS_OPEN ; DOS 4.0
; NLS_LSEEK ; DOS 4.0
; Fake_User_Stack ; DOS 4.0
; GetDevList ; DOS 4.0
; NLS_IOCTL ; DOS 4.0
; NLS_GETEXT ; DOS 4.0
; MSG_RETRIEVAL ; DOS 4.0
; Fake_Version ; DOS 4.0
;
; Revision history:
;
; Created: ARR 30 March 1983
;
; A000 version 4.0 Jan. 1988
; A001 DCR 486 - Share installation for >32mb drives
; A006 DCR 503 - fake version number for IBMCACHE
; DOS 5.00 Moved fake version to caller's PSP
.xlist
.xcref
include version.inc
include dosseg.inc
include dossym.inc
include sysvar.inc
include sf.inc
include curdir.inc
include fastxxxx.inc
include bugtyp.inc
.cref
.list
i_need THISCDS,DWORD
I_Need RetryLoop,WORD
I_need fSharing,BYTE ; TRUE => server-issued call
I_need FastTable,BYTE ;AN000;
I_need FastFlg,BYTE ;AN000;
I_need User_SP_2F,WORD ;AN000;
I_need User_SP,WORD ;AN000;
I_need User_SS,WORD ;AN000;
I_need SysInitTable,BYTE ;AN000;
I_need EXTERR,WORD ;AN000;
I_need MSG_EXTERROR,DWORD ;AN000;
I_need fshare,byte ;AN001;
I_need Special_version,WORD ;AN006;
DOSCODE SEGMENT
allow_getdseg
ASSUME SS:DOSDATA,CS:DOSCODE
Break <STRCMP - compare two ASCIZ strings DS:SI to ES:DI>
;----------------------------------------------------------------------------
;
; Strcmp - compare ASCIZ DS:SI to ES:DI. Case INSENSITIVE. '/' = '\'
; Strings of different lengths don't match.
; Inputs: DS:SI - pointer to source string ES:DI - pointer to dest string
; Outputs: Z if strings same, NZ if different
; Registers modified: NONE
;----------------------------------------------------------------------------
Procedure StrCmp,NEAR
ASSUME CS:DOSCODE,SS:DOSDATA
SAVE <SI,DI,AX>
Cmplp:
LODSB
IFDEF DBCS ;AN000;
invoke testkanj ;AN000;; 2/13/KK
jz notkanj1 ;AN000;; 2/13/KK
dec si ;AN000;; Do source again 2/13/KK
cmpsb ;AN000;; First byte 2/13/KK
JNZ PopRet ;AN000;; Strings dif 2/13/KK
cmpsb ;AN000;; Second byte of kanji char 2/13/KK
JNZ PopRet ;AN000;; Strings dif 2/13/KK
mov al,byte ptr [SI-1] ;AN000;; Need last byte in AL 2/13/KK
jmp short Tend ;AN000;
notkanj1: ;AN000;; 2/13/KK
ENDIF ;AN000;
invoke UCase ; convert to upper case
Invoke PathChrCmp ; convert / to \
MOV AH,AL
MOV AL,ES:[DI]
INC DI
invoke UCase ; convert to upper case
Invoke PathChrCmp ; convert / to \
CMP AH,AL
JNZ PopRet ; Strings dif
Tend:
OR AL,AL
JNZ Cmplp ; More string
PopRet:
RESTORE <AX,DI,SI>
return
EndProc StrCmp
Break <STRCPY - copy ASCIZ string from DS:SI to ES:DI>
;----------------------------------------------------------------------------
;
; Strcpy - copy an ASCIZ string from DS:SI to ES:DI and make uppercase
; FStrcpy - copy an ASCIZ string from DS:SI to ES:DI. no modification of
; characters.
;
; Inputs: DS:SI - pointer to source string
; ES:DI - pointer to destination string
; Outputs: ES:DI point byte after nul byte at end of dest string
; DS:SI point byte after nul byte at end of source string
; Registers modified: SI,DI
;----------------------------------------------------------------------------
Procedure StrCpy,NEAR
ASSUME CS:DOSCODE,SS:DOSDATA
SAVE <AX>
CPYLoop:
LODSB
IFDEF DBCS ;AN000;
invoke testkanj ;AN000;; 2/13/KK
jz notkanj2 ;AN000;; 2/13/KK
STOSB ;AN000;; 2/13/KK
LODSB ;AN000;; 2/13/KK
STOSB ;AN000;; 2/13/KK
jmp short CPYLoop ;AN000;; 3/31/KK
notkanj2: ;AN000;; 2/13/KK
ENDIF ;AN000;
invoke UCase ; convert to upper case
Invoke PathChrCmp ; convert / to \
STOSB
Tend2:
OR AL,AL
JNZ CPYLoop
RESTORE <AX>
return
EndProc StrCpy
;----------------------------------------------------------------------------
; Procedure Name : FStrCpy
;----------------------------------------------------------------------------
Procedure FStrCpy,NEAR
ASSUME CS:DOSCODE,SS:DOSDATA
SAVE <AX>
FCPYLoop:
LODSB
STOSB
OR AL,AL
JNZ FCPYLoop
RESTORE <AX>
return
EndProc FStrCpy
Break <StrLen - compute length of string ES:DI>
;** StrLen - Compute Length of String
;
; StrLen computes the length of a string, including the trailing 00
;
; ENTRY (es:di) = address of string
; EXIT (cx) = size of string
; USES cx, flags
Procedure StrLen,NEAR
ASSUME CS:DOSCODE,SS:DOSDATA
SAVE <di, ax>
MOV CX,-1
XOR AL,AL
REPNE SCASB
NOT CX
RESTORE <ax, di>
return
EndProc StrLen
;** DStrLen - Compute Length of String
;
; ENTRY (ds:si) = address of string
; EXIT (cx) = size of string, including trailing NUL
; USES cx, flags
Procedure DStrLen,NEAR ; BUGBUG - this guy is a pig, who uses him?
CALL XCHGP
CALL StrLen
CALL XCHGP
return
EndProc DStrLen
Break <XCHGP - exchange source and destination pointers>
;** XCHGP - Exchange Pointers
;
; XCHGP exchanges (DS:SI) and (ES:DI)
;
; ENTRY none
; EXIT pairs exchanged
; USES SI, DI, DS, ES
Procedure XCHGP,NEAR
SAVE <DS,ES>
RESTORE <DS,ES>
XCHG SI,DI
return
EndProc XCHGP
Break <Idle - wait for a specified amount of time>
;----------------------------------------------------------------------------
;
; Idle - when retrying an operation due to a lock/sharing violation, we spin
; until RetryLoop is exhausted.
;
; Inputs: RetryLoop is the number of times we spin
; Outputs: Wait
; Registers modified: none
;----------------------------------------------------------------------------
Procedure Idle,NEAR
ASSUME CS:DOSCODE,SS:DOSDATA
;hkn; SS override
cmp fSharing,0
retnz
SAVE <CX>
;hkn; SS override
MOV CX,RetryLoop
JCXZ Idle3
Idle1: PUSH CX
XOR CX,CX
Idle2: LOOP Idle2
POP CX
LOOP Idle1
Idle3: RESTORE <CX>
return
EndProc Idle
Break <TableDispatch - dispatch to a table>
;----------------------------------------------------------------------------
;
; TableDispatch - given a table and an index, jmp to the approptiate
; routine. Preserve all input registers to the routine.
;
; Inputs: Push return address
; Push Table address
; Push index (byte)
; Outputs: appropriate routine gets jumped to.
; return indicates invalid index
; Registers modified: none.
;----------------------------------------------------------------------------
TableFrame STRUC
OldBP DW ?
OldRet DW ?
Index DB ?
Pad DB ?
Tab DW ?
NewRet DW ?
TableFrame ENDS
procedure TableDispatch,NEAR
ASSUME CS:DOSCODE,SS:NOTHING
PUSH BP
MOV BP,SP
PUSH BX ; save BX
MOV BX,[BP.Tab] ; get pointer to table
MOV BL,CS:[BX] ; maximum index
CMP [BP.Index],BL ; table error?
JAE TableError ; yes
MOV BL,[BP.Index] ; get desired table index
XOR BH,BH ; convert to word
SHL BX,1 ; convert to word pointer
INC BX ; point past first length byte
ADD BX,[BP.Tab] ; get real offset
MOV BX,CS:[BX] ; get contents of table entry
MOV [BP.Tab],BX ; put table entry into return address
POP BX ; restore BX
POP BP ; restore BP
ADD SP,4 ; clean off Index and our return addr
return ; do operation
TableError:
POP BX ; restore BX
POP BP ; restore BP
RET 6 ; clean off Index, Table and RetAddr
EndProc TableDispatch
Break <TestNet - determine if a CDS is for the network>
;----------------------------------------------------------------------------
;
; TestNet - examine CDS pointed to by ThisCDS and see if it indicates a
; network CDS. This will handle NULL cds also.
;
; Inputs: ThisCDS points to CDS or NULL
; Outputs: ES:DI = ThisCDS
; carry Set => network
; carry Clear => local
; Registers modified: none.
;----------------------------------------------------------------------------
Procedure TestNet,NEAR
ASSUME CS:DOSCODE,SS:NOTHING
getdseg <es> ; es -> dosdata
LES DI,ThisCDS
assume es:NOTHING
CMP DI,-1
JZ CMCRet ; UNC? carry is clear
TESTB ES:[DI].curdir_flags,curdir_isnet
JNZ CMCret ; jump has carry clear
return ; carry is clear
CMCRet: CMC
return
EndProc TestNet
Break <IsSFTNet - see if an sft is for the network>
;----------------------------------------------------------------------------
;
; IsSFTNet - examine SF pointed to by ES:DI and see if it indicates a
; network file.
;
; Inputs: ES:DI point to SFT
; Outputs: Zero set if not network sft
; zero reset otherwise
; Carry CLEAR!!!
; Registers modified: none.
;----------------------------------------------------------------------------
Procedure IsSFTNet,NEAR
ASSUME CS:DOSCODE,SS:NOTHING
TESTB ES:[DI].sf_flags,sf_isnet
return
EndProc IsSFTNet
Break <FastInit - Initialize FastTable entries >
;----------------------------------------------------------------------------
; DOS 4.00 2/9/87
; FastInit - initialize the FASTXXX routine entry
; in the FastTable
;
; Inputs: BX = FASTXXX ID ( 1=fastopen )
; DS:SI = address of FASTXXX routine entry
; SI = -1 for query only
; Outputs: Carry flag clear, if success
; Carry flag set, if failure
;
;
;----------------------------------------------------------------------------
Procedure FastInit,NEAR
ASSUME CS:DOSCODE,SS:NOTHING
;hkn; set up es to dosdataseg.
push es
getdseg <es> ; es -> dosdata
;hkn; FastTable is in DOSDATA
MOV DI,OFFSET DOSDATA:FastTable + 2 ;AN000;FO. points to fastxxx entry
DEC BX ;AN000;FO.;; decrement index
MOV DX,BX ;AN000;FO.;; save bx
SHL BX,1 ;AN000;FO.;; times 4 , each entry is DWORD
SHL BX,1 ;AN000;FO.
ADD DI,BX ;AN000;FO. index to the entry
MOV AX,WORD PTR ES:[DI+2] ;AN000;FO. get entry segment
fcheck: ;AN000;
MOV CX,CS ;AN000;FO.;; get DOS segment
CMP AX,CX ;AN000;FO.;; first time installed ?
JZ ok_install ;AN000;FO.;; yes
OR AX,AX ;AN000;FO.;
JZ ok_install ;AN000;FO.;
STC ;AN000;FO.;; already installed !
JMP SHORT FSret ;AN000;FO. set carry
ok_install: ;AN000;
CMP SI,-1 ;AN000;FO.; Query only ?
JZ FSret ;AN000;FO.; yes
MOV CX,DS ;AN000;FO.; get FASTXXX entry segment
MOV WORD PTR ES:[DI+2],CX ;AN000;FO.; initialize routine entry
MOV WORD PTR ES:[DI],SI ;AN000;FO.; initialize routine offset
;hkn; FastFlg moved to DOSDATA
MOV DI,OFFSET DOSDATA:FastFlg ;AN000;FO.; get addr of FASTXXX flags
ADD DI,DX ;AN000;FO.; index to a FASTXXX flag
OR byte ptr ES:[DI],Fast_yes ;AN000;FO.; indicate installed
FSret: ;AN000;
pop es
return ;AN000;FO.
EndProc FastInit ;AN000;FO.
Break <FastRet - initial routine in FastOpenTable >
;----------------------------------------------------------------------------
; DOS 3.3 6/10/86
; FastRet - indicate FASTXXXX not in memory
;
; Inputs: None
; Outputs: AX = -1 and carry flag set
;
; Registers modified: none.
;----------------------------------------------------------------------------
Procedure FastRet,FAR
STC
sbb ax,ax ; (ax) = -1, 'C' set
RET
EndProc FastRet
Break <NLS_OPEN - do $open for NLSFUNC >
;----------------------------------------------------------------------------
; DOS 3.3 6/10/86
; NLS_OPEN - call $OPEN for NLSFUNC
;
; Inputs: Same input as $OPEN except CL = mode
; Outputs: same output as $OPEN
;
;----------------------------------------------------------------------------
;hkn; NOTE! SS MUST HAVE BEEN SET UP TO DOSDATA BY THE TIME THESE
;hkn; NLS FUNCTIONS ARE CALLED!!! THERE FORE WE WILL USE SS OVERRIDES
;hkn; IN ORDER TO ACCESS DOS DATA VARIABLES!
Procedure NLS_OPEN,NEAR
ASSUME CS:DOSCODE,SS:NOTHING
; MOV BL,[CPSWFLAG] ; disable code page matching logic
; MOV [CPSWFLAG],0
; PUSH BX ; save current state
MOV AL,CL ; set up correct interface for $OPEN
invoke $OPEN
; POP BX ; restore current state
; MOV [CPSWFLAG],BL
RET
EndProc NLS_OPEN
Break <NLS_LSEEK - do $LSEEK for NLSFUNC >
;----------------------------------------------------------------------------
; DOS 3.3 6/10/86
; NLS_LSEEK - call $LSEEK for NLSFUNC
;
; Inputs: BP = open mode
; Outputs: same output as $LSEEK
;
;----------------------------------------------------------------------------
Procedure NLS_LSEEK,NEAR
ASSUME CS:DOSCODE,SS:NOTHING
PUSH ss:[user_SP] ; save user stack
PUSH ss:[user_SS]
CALL Fake_User_Stack
MOV AX,BP ; set up correct interface for $LSEEK
invoke $LSEEK
POP ss:[user_SS] ; restore user stack
POP ss:[user_SP]
RET
EndProc NLS_LSEEK
Break <Fake_User_Stack - save user stack >
;----------------------------------------------------------------------------
; DOS 3.3 6/10/86
; Fake_User_Stack - save user stack pointer
;
;----------------------------------------------------------------------------
Procedure Fake_User_Stack,NEAR
ASSUME CS:DOSCODE,SS:NOTHING
MOV AX,ss:[User_SP_2F] ; replace with INT 2F stack
MOV ss:[user_SP],AX
;hkn; MOV AX,CS
mov ax, ss
MOV ss:[user_SS],AX ; DOSGROUP
RET
EndProc Fake_User_Stack
;
Break <GetDevList - get device header list pointer>
;----------------------------------------------------------------------------
; DOS 3.3 7/25/86
; GetDevList - get device header list pointer
;
; Output: AX:BX points to the device header list
;----------------------------------------------------------------------------
Procedure GetDevList,NEAR
ASSUME CS:DOSCODE,SS:DOSDATA
MOV SI,OFFSET DOSDATA:SysInitTable
;hkn; set up ds to point to DOSDATA
getdseg <ds> ; ds -> dosdata
LDS SI,[SI.SYSI_InitVars]
MOV AX,WORD PTR DS:[SI.SYSI_DEV]
MOV BX,WORD PTR DS:[SI.SYSI_DEV+2]
RET
EndProc GetDevList
Break <NLS_IOCTL - do $IOCTL for NLSFUNC >
;----------------------------------------------------------------------------
; DOS 3.3 7/25/86
; NLS_IOCTL - call $IOCTL for NLSFUNC
;
; Inputs: BP = function code 0CH
; Outputs: same output as generic $IOCTL
;
;----------------------------------------------------------------------------
Procedure NLS_IOCTL,NEAR
ASSUME CS:DOSCODE,SS:NOTHING
PUSH ss:[user_SP] ; save user stack
PUSH ss:[user_SS]
CALL Fake_User_Stack
MOV AX,BP ; set up correct interface for $LSEEK
invoke $IOCTL
POP ss:[user_SS] ; restore user stack
POP ss:[user_SP]
RET
EndProc NLS_IOCTL
Break <NLS_GETEXT- get extended error for NLSFUNC>
;----------------------------------------------------------------------------
; DOS 3.3 7/25/86
; NLS_GETEXT -
;
; Inputs: none
; Outputs: AX = extended error
;
;----------------------------------------------------------------------------
Procedure NLS_GETEXT,NEAR
ASSUME CS:DOSCODE,SS:NOTHING
MOV AX,SS:[EXTERR] ; return extended error
RET
EndProc NLS_GETEXT
Break <MSG_RETRIEVAL- get beginning addr of system and parser messages>
;----------------------------------------------------------------------------
; DOS 4.00
;
; Inputs: DL=0 get extended error message addr
; =1 set extended error message addr
; =2 get parser error message addr
; =3 set parser error message addr
; =4 get critical error message addr
; =5 set critical error message addr
; =6 get file system error message addr
; =7 set file system error message addr
; =8 get address for code reduction
; =9 set address for code reduction
; Function: get/set message address
; Outputs: ES:DI points to addr when get
;----------------------------------------------------------------------------
Procedure MSG_RETRIEVAL,NEAR
ASSUME CS:DOSCODE,SS:NOTHING
;; NOTE: This function lives in command.com resident code now.
;; If the int 2F ever gets this far, we'll return registers
;; unchanged, which produces the same result as before, if
;; command.com wasn't present (and therefore no messages available).
;;
;; I didn't point the entry in the 2F table to No_Op because
;; No_Op zeroes AL.
;;
;;;hkn; set up ds to point to DOSDATA
;; push ds
;; getdseg <ds> ; ds -> dosdata
;;
;; PUSH AX ;AN000;;MS. save regs
;; PUSH SI ;AN000;;MS. save regs
;; MOV AX,DX ;AN000;;MS.
;; MOV SI,OFFSET DOSDATA:MSG_EXTERROR ;AN000;;MS.
;; test AL,1 ;AN000;;MS. get ?
;; JZ toget ;AN000;;MS. yes
;; DEC AL ;AN000;;MS.
;;toget: ;AN000;
;; SHL AL,1 ;AN000;;MS. times 2
;; XOR AH,AH ;AN000;;MS.
;; ADD SI,AX ;AN000;;MS. position to the entry
;; test DL,1 ;AN000;;MS. get ?
;; JZ getget ;AN000;;MS. yes
;; MOV WORD PTR DS:[SI],DI ;AN000;;MS. set MSG
;; MOV WORD PTR DS:[SI+2],ES ;AN000;;MS. address to ES:DI
;; JMP SHORT MSGret ;AN000;;MS. exit
;;getget: ;AN000;
;; LES DI,DWORD PTR DS:[SI] ;AN000;;MS. get msg addr
;;MSGret: ;AN000;
;; POP SI ;AN000;;MS.
;; POP AX ;AN000;;MS.
;;
;; pop ds
return ;AN000;;MS. exit
EndProc MSG_RETRIEVAL ;AN000;
;***Break <Fake_version - set/reset version flag>
;***;----------------------------------------------------------------------------
;***;
;***; Inputs: DL=0 current version number
;***; <>0 special version number
;***; Function: set special version number
;***; Outputs: version number is changed
;***;
;***;----------------------------------------------------------------------------
;***
;***Procedure Fake_version,NEAR
;*** ASSUME CS:DOSCODE,SS:NOTHING
;***
;***;hkn; set up ds to point to DOSDATA
;*** push ds
;*** getdseg <ds> ; ds -> dosdata
;*** MOV [Special_version],DX ;AN006;MS.
;*** pop ds
;*** return ;AN006;;MS. exit
;***
;***EndProc Fake_version ;AN006;;MS.
DOSCODE ENDS
END
|
; A124861: Expansion of 1/(1-x-3x^2-4x^3-2x^4).
; Submitted by Jon Maiga
; 1,1,4,11,29,80,219,597,1632,4459,12181,33280,90923,248405,678656,1854123,5065557,13839360,37809835,103298389,282216448,771029675,2106492245,5755043840,15723072171,42956232021,117358608384
mov $3,1
lpb $0
sub $0,1
mov $2,$3
add $3,$1
mov $1,$2
mul $3,2
lpe
mov $0,$3
mul $0,4
sub $0,3
div $0,6
add $0,1
|
//
// EntityTree.cpp
// libraries/entities/src
//
// Created by Brad Hefta-Gaub on 12/4/13.
// Copyright 2013 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "EntityTree.h"
#include <QtCore/QDateTime>
#include <QtCore/QQueue>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <NetworkingConstants.h>
#include "AccountManager.h"
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QtScript/QScriptEngine>
#include <Extents.h>
#include <PerfStat.h>
#include <Profile.h>
#include "EntitySimulation.h"
#include "VariantMapToScriptValue.h"
#include "AddEntityOperator.h"
#include "UpdateEntityOperator.h"
#include "QVariantGLM.h"
#include "EntitiesLogging.h"
#include "RecurseOctreeToMapOperator.h"
#include "RecurseOctreeToJSONOperator.h"
#include "LogHandler.h"
#include "EntityEditFilters.h"
#include "EntityDynamicFactoryInterface.h"
static const quint64 DELETED_ENTITIES_EXTRA_USECS_TO_CONSIDER = USECS_PER_MSEC * 50;
const float EntityTree::DEFAULT_MAX_TMP_ENTITY_LIFETIME = 60 * 60; // 1 hour
EntityTree::EntityTree(bool shouldReaverage) :
Octree(shouldReaverage)
{
resetClientEditStats();
EntityItem::retrieveMarketplacePublicKey();
}
EntityTree::~EntityTree() {
// NOTE: to eraseAllOctreeElements() in this context is useless because
// any OctreeElements in the tree still have shared backpointers to this Tree
// which means the dtor never would have been called in the first place!
//
// I'm keeping this useless commented-out line to remind us:
// we don't need shared pointer overhead for EntityTrees.
// TODO: EntityTreeElement::_tree should be raw back pointer.
// AND: EntityItem::_element should be a raw back pointer.
//eraseAllOctreeElements(false); // KEEP THIS
}
void EntityTree::setEntityScriptSourceWhitelist(const QString& entityScriptSourceWhitelist) {
_entityScriptSourceWhitelist = entityScriptSourceWhitelist.split(',', QString::SkipEmptyParts);
}
void EntityTree::createRootElement() {
_rootElement = createNewElement();
}
OctreeElementPointer EntityTree::createNewElement(unsigned char* octalCode) {
auto newElement = EntityTreeElementPointer(new EntityTreeElement(octalCode));
newElement->setTree(std::static_pointer_cast<EntityTree>(shared_from_this()));
return std::static_pointer_cast<OctreeElement>(newElement);
}
void EntityTree::eraseDomainAndNonOwnedEntities() {
emit clearingEntities();
if (_simulation) {
// local entities are not in the simulation, so we clear ALL
_simulation->clearEntities();
}
this->withWriteLock([&] {
QHash<EntityItemID, EntityItemPointer> savedEntities;
// NOTE: lock the Tree first, then lock the _entityMap.
// It should never be done the other way around.
QReadLocker locker(&_entityMapLock);
foreach(EntityItemPointer entity, _entityMap) {
EntityTreeElementPointer element = entity->getElement();
if (element) {
element->cleanupDomainAndNonOwnedEntities();
}
if (entity->isLocalEntity() || (entity->isAvatarEntity() && entity->getOwningAvatarID() == getMyAvatarSessionUUID())) {
savedEntities[entity->getEntityItemID()] = entity;
} else {
int32_t spaceIndex = entity->getSpaceIndex();
if (spaceIndex != -1) {
// stale spaceIndices will be freed later
_staleProxies.push_back(spaceIndex);
}
}
}
_entityMap.swap(savedEntities);
});
resetClientEditStats();
clearDeletedEntities();
{
QWriteLocker locker(&_needsParentFixupLock);
QVector<EntityItemWeakPointer> needParentFixup;
foreach (EntityItemWeakPointer entityItem, _needsParentFixup) {
auto entity = entityItem.lock();
if (entity && (entity->isLocalEntity() || (entity->isAvatarEntity() && entity->getOwningAvatarID() == getMyAvatarSessionUUID()))) {
needParentFixup.push_back(entityItem);
}
}
_needsParentFixup = needParentFixup;
}
}
void EntityTree::eraseAllOctreeElements(bool createNewRoot) {
emit clearingEntities();
if (_simulation) {
_simulation->clearEntities();
}
QHash<EntityItemID, EntityItemPointer> localMap;
localMap.swap(_entityMap);
this->withWriteLock([&] {
foreach(EntityItemPointer entity, localMap) {
EntityTreeElementPointer element = entity->getElement();
if (element) {
element->cleanupEntities();
}
int32_t spaceIndex = entity->getSpaceIndex();
if (spaceIndex != -1) {
// assume stale spaceIndices will be freed later
_staleProxies.push_back(spaceIndex);
}
}
});
localMap.clear();
Octree::eraseAllOctreeElements(createNewRoot);
resetClientEditStats();
clearDeletedEntities();
{
QWriteLocker locker(&_needsParentFixupLock);
_needsParentFixup.clear();
}
}
void EntityTree::readBitstreamToTree(const unsigned char* bitstream,
uint64_t bufferSizeBytes, ReadBitstreamToTreeParams& args) {
Octree::readBitstreamToTree(bitstream, bufferSizeBytes, args);
// add entities
QHash<EntityItemID, EntityItemPointer>::const_iterator itr;
for (itr = _entitiesToAdd.constBegin(); itr != _entitiesToAdd.constEnd(); ++itr) {
const EntityItemPointer& entityItem = itr.value();
AddEntityOperator theOperator(getThisPointer(), entityItem);
recurseTreeWithOperator(&theOperator);
postAddEntity(entityItem);
}
_entitiesToAdd.clear();
// move entities
if (_entityMover.hasMovingEntities()) {
PerformanceTimer perfTimer("recurseTreeWithOperator");
recurseTreeWithOperator(&_entityMover);
_entityMover.reset();
}
}
int EntityTree::readEntityDataFromBuffer(const unsigned char* data, int bytesLeftToRead, ReadBitstreamToTreeParams& args) {
const unsigned char* dataAt = data;
int bytesRead = 0;
uint16_t numberOfEntities = 0;
int expectedBytesPerEntity = EntityItem::expectedBytes();
args.elementsPerPacket++;
if (bytesLeftToRead >= (int)sizeof(numberOfEntities)) {
// read our entities in....
numberOfEntities = *(uint16_t*)dataAt;
dataAt += sizeof(numberOfEntities);
bytesLeftToRead -= (int)sizeof(numberOfEntities);
bytesRead += sizeof(numberOfEntities);
if (bytesLeftToRead >= (int)(numberOfEntities * expectedBytesPerEntity)) {
for (uint16_t i = 0; i < numberOfEntities; i++) {
int bytesForThisEntity = 0;
EntityItemID entityItemID = EntityItemID::readEntityItemIDFromBuffer(dataAt, bytesLeftToRead);
EntityItemPointer entity = findEntityByEntityItemID(entityItemID);
if (entity) {
QString entityScriptBefore = entity->getScript();
QUuid parentIDBefore = entity->getParentID();
QString entityServerScriptsBefore = entity->getServerScripts();
quint64 entityScriptTimestampBefore = entity->getScriptTimestamp();
bytesForThisEntity = entity->readEntityDataFromBuffer(dataAt, bytesLeftToRead, args);
if (entity->getDirtyFlags()) {
entityChanged(entity);
}
_entityMover.addEntityToMoveList(entity, entity->getQueryAACube());
QString entityScriptAfter = entity->getScript();
QString entityServerScriptsAfter = entity->getServerScripts();
quint64 entityScriptTimestampAfter = entity->getScriptTimestamp();
bool reload = entityScriptTimestampBefore != entityScriptTimestampAfter;
// If the script value has changed on us, or it's timestamp has changed to force
// a reload then we want to send out a script changing signal...
if (reload || entityScriptBefore != entityScriptAfter) {
emitEntityScriptChanging(entityItemID, reload); // the entity script has changed
}
if (reload || entityServerScriptsBefore != entityServerScriptsAfter) {
emitEntityServerScriptChanging(entityItemID, reload); // the entity server script has changed
}
QUuid parentIDAfter = entity->getParentID();
if (parentIDBefore != parentIDAfter) {
addToNeedsParentFixupList(entity);
}
} else {
entity = EntityTypes::constructEntityItem(dataAt, bytesLeftToRead);
if (entity) {
bytesForThisEntity = entity->readEntityDataFromBuffer(dataAt, bytesLeftToRead, args);
// don't add if we've recently deleted....
if (!isDeletedEntity(entityItemID)) {
_entitiesToAdd.insert(entityItemID, entity);
if (entity->getCreated() == UNKNOWN_CREATED_TIME) {
entity->recordCreationTime();
}
#ifdef WANT_DEBUG
} else {
qCDebug(entities) << "Received packet for previously deleted entity [" <<
entityItemID << "] ignoring. (inside " << __FUNCTION__ << ")";
#endif
}
}
}
// Move the buffer forward to read more entities
dataAt += bytesForThisEntity;
bytesLeftToRead -= bytesForThisEntity;
bytesRead += bytesForThisEntity;
}
}
}
return bytesRead;
}
bool EntityTree::handlesEditPacketType(PacketType packetType) const {
// we handle these types of "edit" packets
switch (packetType) {
case PacketType::EntityAdd:
case PacketType::EntityClone:
case PacketType::EntityEdit:
case PacketType::EntityErase:
case PacketType::EntityPhysics:
return true;
default:
return false;
}
}
/// Adds a new entity item to the tree
void EntityTree::postAddEntity(EntityItemPointer entity) {
assert(entity);
if (getIsServer()) {
QString certID(entity->getCertificateID());
EntityItemID entityItemID = entity->getEntityItemID();
EntityItemID existingEntityItemID;
{
QWriteLocker locker(&_entityCertificateIDMapLock);
existingEntityItemID = _entityCertificateIDMap.value(certID);
if (!certID.isEmpty()) {
_entityCertificateIDMap.insert(certID, entityItemID);
qCDebug(entities) << "Certificate ID" << certID << "belongs to" << entityItemID;
}
}
// Delete an already-existing entity from the tree if it has the same
// CertificateID as the entity we're trying to add.
if (!existingEntityItemID.isNull()) {
qCDebug(entities) << "Certificate ID" << certID << "already exists on entity with ID"
<< existingEntityItemID << ". Deleting existing entity.";
deleteEntity(existingEntityItemID, true);
return;
}
}
// check to see if we need to simulate this entity..
if (_simulation) {
_simulation->addEntity(entity);
}
if (!entity->getParentID().isNull()) {
addToNeedsParentFixupList(entity);
}
_isDirty = true;
// find and hook up any entities with this entity as a (previously) missing parent
fixupNeedsParentFixups();
emit addingEntity(entity->getEntityItemID());
emit addingEntityPointer(entity.get());
}
bool EntityTree::updateEntity(const EntityItemID& entityID, const EntityItemProperties& properties, const SharedNodePointer& senderNode) {
EntityItemPointer entity;
{
QReadLocker locker(&_entityMapLock);
entity = _entityMap.value(entityID);
}
if (!entity) {
return false;
}
return updateEntity(entity, properties, senderNode);
}
bool EntityTree::updateEntity(EntityItemPointer entity, const EntityItemProperties& origProperties,
const SharedNodePointer& senderNode) {
EntityTreeElementPointer containingElement = entity->getElement();
if (!containingElement) {
return false;
}
EntityItemProperties properties = origProperties;
bool allowLockChange;
QUuid senderID;
if (senderNode.isNull()) {
auto nodeList = DependencyManager::get<NodeList>();
allowLockChange = nodeList->isAllowedEditor();
senderID = nodeList->getSessionUUID();
} else {
allowLockChange = senderNode->isAllowedEditor();
senderID = senderNode->getUUID();
}
if (!allowLockChange && (entity->getLocked() != properties.getLocked())) {
qCDebug(entities) << "Refusing disallowed lock adjustment.";
return false;
}
// enforce support for locked entities. If an entity is currently locked, then the only
// property we allow you to change is the locked property.
if (entity->getLocked()) {
if (properties.lockedChanged()) {
bool wantsLocked = properties.getLocked();
if (!wantsLocked) {
EntityItemProperties tempProperties;
tempProperties.setLocked(wantsLocked);
tempProperties.setLastEdited(properties.getLastEdited());
bool success;
AACube queryCube = entity->getQueryAACube(success);
if (!success) {
qCWarning(entities) << "failed to get query-cube for" << entity->getID();
}
UpdateEntityOperator theOperator(getThisPointer(), containingElement, entity, queryCube);
recurseTreeWithOperator(&theOperator);
if (entity->setProperties(tempProperties)) {
emit editingEntityPointer(entity);
}
_isDirty = true;
}
}
} else {
if (getIsServer()) {
bool simulationBlocked = !entity->getSimulatorID().isNull();
if (properties.simulationOwnerChanged()) {
QUuid submittedID = properties.getSimulationOwner().getID();
// a legit interface will only submit their own ID or NULL:
if (submittedID.isNull()) {
if (entity->getSimulatorID() == senderID) {
// We only allow the simulation owner to clear their own simulationID's.
simulationBlocked = false;
properties.clearSimulationOwner(); // clear everything
}
// else: We assume the sender really did believe it was the simulation owner when it sent
} else if (submittedID == senderID) {
// the sender is trying to take or continue ownership
if (entity->getSimulatorID().isNull()) {
// the sender is taking ownership
if (properties.getSimulationOwner().getPriority() == VOLUNTEER_SIMULATION_PRIORITY) {
// the entity-server always promotes VOLUNTEER to RECRUIT to avoid ownership thrash
// when dynamic objects first activate and multiple participants bid simultaneously
properties.setSimulationPriority(RECRUIT_SIMULATION_PRIORITY);
}
simulationBlocked = false;
} else if (entity->getSimulatorID() == senderID) {
// the sender is asserting ownership, maybe changing priority
simulationBlocked = false;
// the entity-server always promotes VOLUNTEER to RECRUIT to avoid ownership thrash
// when dynamic objects first activate and multiple participants bid simultaneously
if (properties.getSimulationOwner().getPriority() == VOLUNTEER_SIMULATION_PRIORITY) {
properties.setSimulationPriority(RECRUIT_SIMULATION_PRIORITY);
}
} else {
// the sender is trying to steal ownership from another simulator
// so we apply the rules for ownership change:
// (1) higher priority wins
// (2) equal priority wins if ownership filter has expired
// (3) VOLUNTEER priority is promoted to RECRUIT
uint8_t oldPriority = entity->getSimulationPriority();
uint8_t newPriority = properties.getSimulationOwner().getPriority();
if (newPriority > oldPriority ||
(newPriority == oldPriority && properties.getSimulationOwner().hasExpired())) {
simulationBlocked = false;
if (properties.getSimulationOwner().getPriority() == VOLUNTEER_SIMULATION_PRIORITY) {
properties.setSimulationPriority(RECRUIT_SIMULATION_PRIORITY);
}
}
}
if (!simulationBlocked) {
entity->setSimulationOwnershipExpiry(usecTimestampNow() + MAX_INCOMING_SIMULATION_UPDATE_PERIOD);
}
} else {
// the entire update is suspect --> ignore it
return false;
}
} else if (simulationBlocked) {
simulationBlocked = senderID != entity->getSimulatorID();
if (!simulationBlocked) {
entity->setSimulationOwnershipExpiry(usecTimestampNow() + MAX_INCOMING_SIMULATION_UPDATE_PERIOD);
}
}
if (simulationBlocked) {
// squash ownership and physics-related changes.
// TODO? replace these eight calls with just one?
properties.setSimulationOwnerChanged(false);
properties.setPositionChanged(false);
properties.setRotationChanged(false);
properties.setVelocityChanged(false);
properties.setAngularVelocityChanged(false);
properties.setAccelerationChanged(false);
properties.setParentIDChanged(false);
properties.setParentJointIndexChanged(false);
if (wantTerseEditLogging()) {
qCDebug(entities) << (senderNode ? senderNode->getUUID() : "null") << "physical edits suppressed";
}
}
}
// else client accepts what the server says
QString entityScriptBefore = entity->getScript();
quint64 entityScriptTimestampBefore = entity->getScriptTimestamp();
uint32_t preFlags = entity->getDirtyFlags();
AACube newQueryAACube;
if (properties.queryAACubeChanged()) {
newQueryAACube = properties.getQueryAACube();
} else {
newQueryAACube = entity->getQueryAACube();
}
UpdateEntityOperator theOperator(getThisPointer(), containingElement, entity, newQueryAACube);
recurseTreeWithOperator(&theOperator);
if (entity->setProperties(properties)) {
emit editingEntityPointer(entity);
}
// if the entity has children, run UpdateEntityOperator on them. If the children have children, recurse
QQueue<SpatiallyNestablePointer> toProcess;
foreach (SpatiallyNestablePointer child, entity->getChildren()) {
if (child && child->getNestableType() == NestableType::Entity) {
toProcess.enqueue(child);
}
}
while (!toProcess.empty()) {
EntityItemPointer childEntity = std::static_pointer_cast<EntityItem>(toProcess.dequeue());
if (!childEntity) {
continue;
}
EntityTreeElementPointer childContainingElement = childEntity->getElement();
if (!childContainingElement) {
continue;
}
bool success;
AACube queryCube = childEntity->getQueryAACube(success);
if (!success) {
addToNeedsParentFixupList(childEntity);
continue;
}
if (!childEntity->getParentID().isNull()) {
addToNeedsParentFixupList(childEntity);
}
UpdateEntityOperator theChildOperator(getThisPointer(), childContainingElement, childEntity, queryCube);
recurseTreeWithOperator(&theChildOperator);
foreach (SpatiallyNestablePointer childChild, childEntity->getChildren()) {
if (childChild && childChild->getNestableType() == NestableType::Entity) {
toProcess.enqueue(childChild);
}
}
}
_isDirty = true;
uint32_t newFlags = entity->getDirtyFlags() & ~preFlags;
if (newFlags) {
if (entity->isSimulated()) {
assert((bool)_simulation);
if (newFlags & DIRTY_SIMULATION_FLAGS) {
_simulation->changeEntity(entity);
}
} else {
// normally the _simulation clears ALL dirtyFlags, but when not possible we do it explicitly
entity->clearDirtyFlags();
}
}
QString entityScriptAfter = entity->getScript();
quint64 entityScriptTimestampAfter = entity->getScriptTimestamp();
bool reload = entityScriptTimestampBefore != entityScriptTimestampAfter;
if (entityScriptBefore != entityScriptAfter || reload) {
emitEntityScriptChanging(entity->getEntityItemID(), reload); // the entity script has changed
}
}
// TODO: this final containingElement check should eventually be removed (or wrapped in an #ifdef DEBUG).
if (!entity->getElement()) {
qCWarning(entities) << "EntityTree::updateEntity() we no longer have a containing element for entityID="
<< entity->getEntityItemID();
return false;
}
return true;
}
EntityItemPointer EntityTree::addEntity(const EntityItemID& entityID, const EntityItemProperties& properties, bool isClone) {
EntityItemProperties props = properties;
auto nodeList = DependencyManager::get<NodeList>();
if (!nodeList) {
qCDebug(entities) << "EntityTree::addEntity -- can't get NodeList";
return nullptr;
}
if (properties.getEntityHostType() == entity::HostType::DOMAIN && getIsClient() &&
!nodeList->getThisNodeCanRez() && !nodeList->getThisNodeCanRezTmp() &&
!nodeList->getThisNodeCanRezCertified() && !nodeList->getThisNodeCanRezTmpCertified() && !_serverlessDomain && !isClone) {
return nullptr;
}
bool recordCreationTime = false;
if (props.getCreated() == UNKNOWN_CREATED_TIME) {
// the entity's creation time was not specified in properties, which means this is a NEW entity
// and we must record its creation time
recordCreationTime = true;
}
// You should not call this on existing entities that are already part of the tree! Call updateEntity()
EntityTreeElementPointer containingElement = getContainingElement(entityID);
if (containingElement) {
qCWarning(entities) << "EntityTree::addEntity() on existing entity item with entityID=" << entityID
<< "containingElement=" << containingElement.get();
return nullptr;
}
// construct the instance of the entity
EntityTypes::EntityType type = props.getType();
EntityItemPointer result = EntityTypes::constructEntityItem(type, entityID, props);
if (result) {
if (recordCreationTime) {
result->recordCreationTime();
}
// Recurse the tree and store the entity in the correct tree element
AddEntityOperator theOperator(getThisPointer(), result);
recurseTreeWithOperator(&theOperator);
postAddEntity(result);
}
return result;
}
void EntityTree::emitEntityScriptChanging(const EntityItemID& entityItemID, bool reload) {
emit entityScriptChanging(entityItemID, reload);
}
void EntityTree::emitEntityServerScriptChanging(const EntityItemID& entityItemID, bool reload) {
emit entityServerScriptChanging(entityItemID, reload);
}
void EntityTree::notifyNewCollisionSoundURL(const QString& newURL, const EntityItemID& entityID) {
emit newCollisionSoundURL(QUrl(newURL), entityID);
}
void EntityTree::setSimulation(EntitySimulationPointer simulation) {
this->withWriteLock([&] {
if (simulation) {
// assert that the simulation's backpointer has already been properly connected
assert(simulation->getEntityTree().get() == this);
}
if (_simulation && _simulation != simulation) {
_simulation->clearEntities();
}
_simulation = simulation;
});
}
void EntityTree::deleteEntity(const EntityItemID& entityID, bool force, bool ignoreWarnings) {
EntityTreeElementPointer containingElement = getContainingElement(entityID);
if (!containingElement) {
if (!ignoreWarnings) {
qCWarning(entities) << "EntityTree::deleteEntity() on non-existent entityID=" << entityID;
}
return;
}
EntityItemPointer existingEntity = containingElement->getEntityWithEntityItemID(entityID);
if (!existingEntity) {
if (!ignoreWarnings) {
qCWarning(entities) << "EntityTree::deleteEntity() on non-existant entity item with entityID=" << entityID;
}
return;
}
if (existingEntity->getLocked() && !force) {
if (!ignoreWarnings) {
qCDebug(entities) << "ERROR! EntityTree::deleteEntity() trying to delete locked entity. entityID=" << entityID;
}
return;
}
cleanupCloneIDs(entityID);
unhookChildAvatar(entityID);
emit deletingEntity(entityID);
emit deletingEntityPointer(existingEntity.get());
// NOTE: callers must lock the tree before using this method
DeleteEntityOperator theOperator(getThisPointer(), entityID);
existingEntity->forEachDescendant([&](SpatiallyNestablePointer descendant) {
auto descendantID = descendant->getID();
theOperator.addEntityIDToDeleteList(descendantID);
emit deletingEntity(descendantID);
EntityItemPointer descendantEntity = std::dynamic_pointer_cast<EntityItem>(descendant);
if (descendantEntity) {
emit deletingEntityPointer(descendantEntity.get());
}
});
recurseTreeWithOperator(&theOperator);
processRemovedEntities(theOperator);
_isDirty = true;
}
void EntityTree::unhookChildAvatar(const EntityItemID entityID) {
EntityItemPointer entity = findEntityByEntityItemID(entityID);
entity->forEachDescendant([&](SpatiallyNestablePointer child) {
if (child->getNestableType() == NestableType::Avatar) {
child->setParentID(nullptr);
}
});
}
void EntityTree::cleanupCloneIDs(const EntityItemID& entityID) {
EntityItemPointer entity = findEntityByEntityItemID(entityID);
if (entity) {
// remove clone ID from its clone origin's clone ID list if clone origin exists
const QUuid& cloneOriginID = entity->getCloneOriginID();
if (!cloneOriginID.isNull()) {
EntityItemPointer cloneOrigin = findEntityByID(cloneOriginID);
if (cloneOrigin) {
cloneOrigin->removeCloneID(entityID);
}
}
// clear the clone origin ID on any clones that this entity had
const QVector<QUuid>& cloneIDs = entity->getCloneIDs();
foreach(const QUuid& cloneChildID, cloneIDs) {
EntityItemPointer cloneChild = findEntityByEntityItemID(cloneChildID);
if (cloneChild) {
cloneChild->setCloneOriginID(QUuid());
}
}
}
}
void EntityTree::deleteEntities(QSet<EntityItemID> entityIDs, bool force, bool ignoreWarnings) {
// NOTE: callers must lock the tree before using this method
DeleteEntityOperator theOperator(getThisPointer());
foreach(const EntityItemID& entityID, entityIDs) {
EntityTreeElementPointer containingElement = getContainingElement(entityID);
if (!containingElement) {
if (!ignoreWarnings) {
qCWarning(entities) << "EntityTree::deleteEntities() on non-existent entityID=" << entityID;
}
continue;
}
EntityItemPointer existingEntity = containingElement->getEntityWithEntityItemID(entityID);
if (!existingEntity) {
if (!ignoreWarnings) {
qCWarning(entities) << "EntityTree::deleteEntities() on non-existent entity item with entityID=" << entityID;
}
continue;
}
if (existingEntity->getLocked() && !force) {
if (!ignoreWarnings) {
qCDebug(entities) << "ERROR! EntityTree::deleteEntities() trying to delete locked entity. entityID=" << entityID;
}
continue;
}
// tell our delete operator about this entityID
cleanupCloneIDs(entityID);
unhookChildAvatar(entityID);
theOperator.addEntityIDToDeleteList(entityID);
emit deletingEntity(entityID);
emit deletingEntityPointer(existingEntity.get());
}
if (!theOperator.getEntities().empty()) {
recurseTreeWithOperator(&theOperator);
processRemovedEntities(theOperator);
_isDirty = true;
}
}
void EntityTree::processRemovedEntities(const DeleteEntityOperator& theOperator) {
quint64 deletedAt = usecTimestampNow();
const RemovedEntities& entities = theOperator.getEntities();
foreach(const EntityToDeleteDetails& details, entities) {
EntityItemPointer theEntity = details.entity;
if (getIsServer()) {
QSet<EntityItemID> childrenIDs;
theEntity->forEachChild([&](SpatiallyNestablePointer child) {
if (child->getNestableType() == NestableType::Entity) {
childrenIDs += child->getID();
}
});
deleteEntities(childrenIDs, true, true);
}
theEntity->die();
if (getIsServer()) {
{
QWriteLocker entityCertificateIDMapLocker(&_entityCertificateIDMapLock);
QString certID = theEntity->getCertificateID();
if (theEntity->getEntityItemID() == _entityCertificateIDMap.value(certID)) {
_entityCertificateIDMap.remove(certID);
}
}
// set up the deleted entities ID
QWriteLocker recentlyDeletedEntitiesLocker(&_recentlyDeletedEntitiesLock);
_recentlyDeletedEntityItemIDs.insert(deletedAt, theEntity->getEntityItemID());
} else {
// on the client side, we also remember that we deleted this entity, we don't care about the time
trackDeletedEntity(theEntity->getEntityItemID());
}
if (theEntity->isSimulated()) {
_simulation->prepareEntityForDelete(theEntity);
}
int32_t spaceIndex = theEntity->getSpaceIndex();
if (spaceIndex != -1) {
// stale spaceIndices will be freed later
_staleProxies.push_back(spaceIndex);
}
}
}
class RayArgs {
public:
// Inputs
glm::vec3 origin;
glm::vec3 direction;
glm::vec3 invDirection;
const QVector<EntityItemID>& entityIdsToInclude;
const QVector<EntityItemID>& entityIdsToDiscard;
PickFilter searchFilter;
// Outputs
OctreeElementPointer& element;
float& distance;
BoxFace& face;
glm::vec3& surfaceNormal;
QVariantMap& extraInfo;
EntityItemID entityID;
};
bool evalRayIntersectionOp(const OctreeElementPointer& element, void* extraData) {
RayArgs* args = static_cast<RayArgs*>(extraData);
bool keepSearching = true;
EntityTreeElementPointer entityTreeElementPointer = std::static_pointer_cast<EntityTreeElement>(element);
EntityItemID entityID = entityTreeElementPointer->evalRayIntersection(args->origin, args->direction,
args->element, args->distance, args->face, args->surfaceNormal, args->entityIdsToInclude,
args->entityIdsToDiscard, args->searchFilter, args->extraInfo);
if (!entityID.isNull()) {
args->entityID = entityID;
// We recurse OctreeElements in order, so if we hit something, we can stop immediately
keepSearching = false;
}
return keepSearching;
}
float evalRayIntersectionSortingOp(const OctreeElementPointer& element, void* extraData) {
RayArgs* args = static_cast<RayArgs*>(extraData);
EntityTreeElementPointer entityTreeElementPointer = std::static_pointer_cast<EntityTreeElement>(element);
float distance = FLT_MAX;
// If origin is inside the cube, always check this element first
if (entityTreeElementPointer->getAACube().contains(args->origin)) {
distance = 0.0f;
} else {
float boundDistance = FLT_MAX;
BoxFace face;
glm::vec3 surfaceNormal;
if (entityTreeElementPointer->getAACube().findRayIntersection(args->origin, args->direction, args->invDirection, boundDistance, face, surfaceNormal)) {
// Don't add this cell if it's already farther than our best distance so far
if (boundDistance < args->distance) {
distance = boundDistance;
}
}
}
return distance;
}
EntityItemID EntityTree::evalRayIntersection(const glm::vec3& origin, const glm::vec3& direction,
QVector<EntityItemID> entityIdsToInclude, QVector<EntityItemID> entityIdsToDiscard,
PickFilter searchFilter, OctreeElementPointer& element, float& distance,
BoxFace& face, glm::vec3& surfaceNormal, QVariantMap& extraInfo,
Octree::lockType lockType, bool* accurateResult) {
RayArgs args = { origin, direction, 1.0f / direction, entityIdsToInclude, entityIdsToDiscard,
searchFilter, element, distance, face, surfaceNormal, extraInfo, EntityItemID() };
distance = FLT_MAX;
bool requireLock = lockType == Octree::Lock;
bool lockResult = withReadLock([&]{
recurseTreeWithOperationSorted(evalRayIntersectionOp, evalRayIntersectionSortingOp, &args);
}, requireLock);
if (accurateResult) {
*accurateResult = lockResult; // if user asked to accuracy or result, let them know this is accurate
}
return args.entityID;
}
class ParabolaArgs {
public:
// Inputs
glm::vec3 origin;
glm::vec3 velocity;
glm::vec3 acceleration;
const QVector<EntityItemID>& entityIdsToInclude;
const QVector<EntityItemID>& entityIdsToDiscard;
PickFilter searchFilter;
// Outputs
OctreeElementPointer& element;
float& parabolicDistance;
BoxFace& face;
glm::vec3& surfaceNormal;
QVariantMap& extraInfo;
EntityItemID entityID;
};
bool evalParabolaIntersectionOp(const OctreeElementPointer& element, void* extraData) {
ParabolaArgs* args = static_cast<ParabolaArgs*>(extraData);
bool keepSearching = true;
EntityTreeElementPointer entityTreeElementPointer = std::static_pointer_cast<EntityTreeElement>(element);
EntityItemID entityID = entityTreeElementPointer->evalParabolaIntersection(args->origin, args->velocity, args->acceleration,
args->element, args->parabolicDistance, args->face, args->surfaceNormal, args->entityIdsToInclude,
args->entityIdsToDiscard, args->searchFilter, args->extraInfo);
if (!entityID.isNull()) {
args->entityID = entityID;
// We recurse OctreeElements in order, so if we hit something, we can stop immediately
keepSearching = false;
}
return keepSearching;
}
float evalParabolaIntersectionSortingOp(const OctreeElementPointer& element, void* extraData) {
ParabolaArgs* args = static_cast<ParabolaArgs*>(extraData);
EntityTreeElementPointer entityTreeElementPointer = std::static_pointer_cast<EntityTreeElement>(element);
float distance = FLT_MAX;
// If origin is inside the cube, always check this element first
if (entityTreeElementPointer->getAACube().contains(args->origin)) {
distance = 0.0f;
} else {
float boundDistance = FLT_MAX;
BoxFace face;
glm::vec3 surfaceNormal;
if (entityTreeElementPointer->getAACube().findParabolaIntersection(args->origin, args->velocity, args->acceleration, boundDistance, face, surfaceNormal)) {
// Don't add this cell if it's already farther than our best distance so far
if (boundDistance < args->parabolicDistance) {
distance = boundDistance;
}
}
}
return distance;
}
EntityItemID EntityTree::evalParabolaIntersection(const PickParabola& parabola,
QVector<EntityItemID> entityIdsToInclude, QVector<EntityItemID> entityIdsToDiscard,
PickFilter searchFilter,
OctreeElementPointer& element, glm::vec3& intersection, float& distance, float& parabolicDistance,
BoxFace& face, glm::vec3& surfaceNormal, QVariantMap& extraInfo,
Octree::lockType lockType, bool* accurateResult) {
ParabolaArgs args = { parabola.origin, parabola.velocity, parabola.acceleration, entityIdsToInclude, entityIdsToDiscard,
searchFilter, element, parabolicDistance, face, surfaceNormal, extraInfo, EntityItemID() };
parabolicDistance = FLT_MAX;
distance = FLT_MAX;
bool requireLock = lockType == Octree::Lock;
bool lockResult = withReadLock([&] {
recurseTreeWithOperationSorted(evalParabolaIntersectionOp, evalParabolaIntersectionSortingOp, &args);
}, requireLock);
if (accurateResult) {
*accurateResult = lockResult; // if user asked to accuracy or result, let them know this is accurate
}
if (!args.entityID.isNull()) {
intersection = parabola.origin + parabola.velocity * parabolicDistance + 0.5f * parabola.acceleration * parabolicDistance * parabolicDistance;
distance = glm::distance(intersection, parabola.origin);
}
return args.entityID;
}
class FindClosestEntityArgs {
public:
// Inputs
glm::vec3 position;
float targetRadius;
PickFilter searchFilter;
// Outputs
QUuid closestEntity;
float closestEntityDistance;
};
bool evalClosestEntityOperation(const OctreeElementPointer& element, void* extraData) {
FindClosestEntityArgs* args = static_cast<FindClosestEntityArgs*>(extraData);
EntityTreeElementPointer entityTreeElement = std::static_pointer_cast<EntityTreeElement>(element);
glm::vec3 penetration;
bool sphereIntersection = entityTreeElement->getAACube().findSpherePenetration(args->position, args->targetRadius, penetration);
// If this entityTreeElement contains the point, then search it...
if (sphereIntersection) {
float closestDistanceSquared = FLT_MAX;
QUuid thisClosestEntity = entityTreeElement->evalClosetEntity(args->position, args->searchFilter, closestDistanceSquared);
// we may have gotten NULL back, meaning no entity was available
if (!thisClosestEntity.isNull()) {
float distanceFromPointToEntity = glm::sqrt(closestDistanceSquared);
// If we're within our target radius
if (distanceFromPointToEntity <= args->targetRadius) {
// we are closer than anything else we've found
if (distanceFromPointToEntity < args->closestEntityDistance) {
args->closestEntity = thisClosestEntity;
args->closestEntityDistance = distanceFromPointToEntity;
}
}
}
// we should be able to optimize this...
return true; // keep searching in case children have closer entities
}
// if this element doesn't contain the point, then none of its children can contain the point, so stop searching
return false;
}
// NOTE: assumes caller has handled locking
QUuid EntityTree::evalClosestEntity(const glm::vec3& position, float targetRadius, PickFilter searchFilter) {
FindClosestEntityArgs args = { position, targetRadius, searchFilter, QUuid(), FLT_MAX };
recurseTreeWithOperation(evalClosestEntityOperation, &args);
return args.closestEntity;
}
class FindEntitiesInSphereArgs {
public:
// Inputs
glm::vec3 position;
float targetRadius;
PickFilter searchFilter;
// Outputs
QVector<QUuid> entities;
};
bool evalInSphereOperation(const OctreeElementPointer& element, void* extraData) {
FindEntitiesInSphereArgs* args = static_cast<FindEntitiesInSphereArgs*>(extraData);
glm::vec3 penetration;
bool sphereIntersection = element->getAACube().findSpherePenetration(args->position, args->targetRadius, penetration);
// If this element contains the point, then search it...
if (sphereIntersection) {
EntityTreeElementPointer entityTreeElement = std::static_pointer_cast<EntityTreeElement>(element);
entityTreeElement->evalEntitiesInSphere(args->position, args->targetRadius, args->searchFilter, args->entities);
return true; // keep searching in case children have closer entities
}
// if this element doesn't contain the point, then none of it's children can contain the point, so stop searching
return false;
}
// NOTE: assumes caller has handled locking
void EntityTree::evalEntitiesInSphere(const glm::vec3& center, float radius, PickFilter searchFilter, QVector<QUuid>& foundEntities) {
FindEntitiesInSphereArgs args = { center, radius, searchFilter, QVector<QUuid>() };
recurseTreeWithOperation(evalInSphereOperation, &args);
foundEntities.swap(args.entities);
}
class FindEntitiesInSphereWithTypeArgs {
public:
// Inputs
glm::vec3 position;
float targetRadius;
EntityTypes::EntityType type;
PickFilter searchFilter;
// Outputs
QVector<QUuid> entities;
};
bool evalInSphereWithTypeOperation(const OctreeElementPointer& element, void* extraData) {
FindEntitiesInSphereWithTypeArgs* args = static_cast<FindEntitiesInSphereWithTypeArgs*>(extraData);
glm::vec3 penetration;
bool sphereIntersection = element->getAACube().findSpherePenetration(args->position, args->targetRadius, penetration);
// If this element contains the point, then search it...
if (sphereIntersection) {
EntityTreeElementPointer entityTreeElement = std::static_pointer_cast<EntityTreeElement>(element);
entityTreeElement->evalEntitiesInSphereWithType(args->position, args->targetRadius, args->type, args->searchFilter, args->entities);
return true; // keep searching in case children have closer entities
}
// if this element doesn't contain the point, then none of it's children can contain the point, so stop searching
return false;
}
// NOTE: assumes caller has handled locking
void EntityTree::evalEntitiesInSphereWithType(const glm::vec3& center, float radius, EntityTypes::EntityType type, PickFilter searchFilter, QVector<QUuid>& foundEntities) {
FindEntitiesInSphereWithTypeArgs args = { center, radius, type, searchFilter, QVector<QUuid>() };
recurseTreeWithOperation(evalInSphereWithTypeOperation, &args);
foundEntities.swap(args.entities);
}
class FindEntitiesInSphereWithNameArgs {
public:
// Inputs
glm::vec3 position;
float targetRadius;
QString name;
bool caseSensitive;
PickFilter searchFilter;
// Outputs
QVector<QUuid> entities;
};
bool evalInSphereWithNameOperation(const OctreeElementPointer& element, void* extraData) {
FindEntitiesInSphereWithNameArgs* args = static_cast<FindEntitiesInSphereWithNameArgs*>(extraData);
glm::vec3 penetration;
bool sphereIntersection = element->getAACube().findSpherePenetration(args->position, args->targetRadius, penetration);
// If this element contains the point, then search it...
if (sphereIntersection) {
EntityTreeElementPointer entityTreeElement = std::static_pointer_cast<EntityTreeElement>(element);
entityTreeElement->evalEntitiesInSphereWithName(args->position, args->targetRadius, args->name, args->caseSensitive, args->searchFilter, args->entities);
return true; // keep searching in case children have closer entities
}
// if this element doesn't contain the point, then none of it's children can contain the point, so stop searching
return false;
}
// NOTE: assumes caller has handled locking
void EntityTree::evalEntitiesInSphereWithName(const glm::vec3& center, float radius, const QString& name, bool caseSensitive, PickFilter searchFilter, QVector<QUuid>& foundEntities) {
FindEntitiesInSphereWithNameArgs args = { center, radius, name, caseSensitive, searchFilter, QVector<QUuid>() };
recurseTreeWithOperation(evalInSphereWithNameOperation, &args);
foundEntities.swap(args.entities);
}
class FindEntitiesInCubeArgs {
public:
// Inputs
AACube cube;
PickFilter searchFilter;
// Outputs
QVector<QUuid> entities;
};
bool findInCubeOperation(const OctreeElementPointer& element, void* extraData) {
FindEntitiesInCubeArgs* args = static_cast<FindEntitiesInCubeArgs*>(extraData);
if (element->getAACube().touches(args->cube)) {
EntityTreeElementPointer entityTreeElement = std::static_pointer_cast<EntityTreeElement>(element);
entityTreeElement->evalEntitiesInCube(args->cube, args->searchFilter, args->entities);
return true;
}
return false;
}
// NOTE: assumes caller has handled locking
void EntityTree::evalEntitiesInCube(const AACube& cube, PickFilter searchFilter, QVector<QUuid>& foundEntities) {
FindEntitiesInCubeArgs args { cube, searchFilter, QVector<QUuid>() };
recurseTreeWithOperation(findInCubeOperation, &args);
foundEntities.swap(args.entities);
}
class FindEntitiesInBoxArgs {
public:
// Inputs
AABox box;
PickFilter searchFilter;
// Outputs
QVector<QUuid> entities;
};
bool findInBoxOperation(const OctreeElementPointer& element, void* extraData) {
FindEntitiesInBoxArgs* args = static_cast<FindEntitiesInBoxArgs*>(extraData);
if (element->getAACube().touches(args->box)) {
EntityTreeElementPointer entityTreeElement = std::static_pointer_cast<EntityTreeElement>(element);
entityTreeElement->evalEntitiesInBox(args->box, args->searchFilter, args->entities);
return true;
}
return false;
}
// NOTE: assumes caller has handled locking
void EntityTree::evalEntitiesInBox(const AABox& box, PickFilter searchFilter, QVector<QUuid>& foundEntities) {
FindEntitiesInBoxArgs args { box, searchFilter, QVector<QUuid>() };
// NOTE: This should use recursion, since this is a spatial operation
recurseTreeWithOperation(findInBoxOperation, &args);
// swap the two lists of entity pointers instead of copy
foundEntities.swap(args.entities);
}
class FindEntitiesInFrustumArgs {
public:
// Inputs
ViewFrustum frustum;
PickFilter searchFilter;
// Outputs
QVector<QUuid> entities;
};
bool findInFrustumOperation(const OctreeElementPointer& element, void* extraData) {
FindEntitiesInFrustumArgs* args = static_cast<FindEntitiesInFrustumArgs*>(extraData);
if (element->isInView(args->frustum)) {
EntityTreeElementPointer entityTreeElement = std::static_pointer_cast<EntityTreeElement>(element);
entityTreeElement->evalEntitiesInFrustum(args->frustum, args->searchFilter, args->entities);
return true;
}
return false;
}
// NOTE: assumes caller has handled locking
void EntityTree::evalEntitiesInFrustum(const ViewFrustum& frustum, PickFilter searchFilter, QVector<QUuid>& foundEntities) {
FindEntitiesInFrustumArgs args = { frustum, searchFilter, QVector<QUuid>() };
// NOTE: This should use recursion, since this is a spatial operation
recurseTreeWithOperation(findInFrustumOperation, &args);
// swap the two lists of entity pointers instead of copy
foundEntities.swap(args.entities);
}
EntityItemPointer EntityTree::findEntityByID(const QUuid& id) const {
EntityItemID entityID(id);
return findEntityByEntityItemID(entityID);
}
EntityItemPointer EntityTree::findEntityByEntityItemID(const EntityItemID& entityID) const {
EntityItemPointer foundEntity = nullptr;
{
QReadLocker locker(&_entityMapLock);
foundEntity = _entityMap.value(entityID);
}
if (foundEntity && !foundEntity->getElement()) {
// special case to maintain legacy behavior:
// if the entity is in the map but not in the tree
// then pretend the entity doesn't exist
return EntityItemPointer(nullptr);
} else {
return foundEntity;
}
}
void EntityTree::fixupTerseEditLogging(EntityItemProperties& properties, QList<QString>& changedProperties) {
static quint64 lastTerseLog = 0;
quint64 now = usecTimestampNow();
if (now - lastTerseLog > USECS_PER_SECOND) {
qCDebug(entities) << "-------------------------";
}
lastTerseLog = now;
if (properties.simulationOwnerChanged()) {
int simIndex = changedProperties.indexOf("simulationOwner");
if (simIndex >= 0) {
SimulationOwner simOwner = properties.getSimulationOwner();
changedProperties[simIndex] = QString("simulationOwner:") + QString::number((int)simOwner.getPriority());
}
}
if (properties.velocityChanged()) {
int index = changedProperties.indexOf("velocity");
if (index >= 0) {
glm::vec3 value = properties.getVelocity();
changedProperties[index] = QString("velocity:") +
QString::number((int)value.x) + "," +
QString::number((int)value.y) + "," +
QString::number((int)value.z);
}
}
if (properties.gravityChanged()) {
int index = changedProperties.indexOf("gravity");
if (index >= 0) {
glm::vec3 value = properties.getGravity();
QString changeHint = "0";
if (value.x + value.y + value.z > 0) {
changeHint = "+";
} else if (value.x + value.y + value.z < 0) {
changeHint = "-";
}
changedProperties[index] = QString("gravity:") + changeHint;
}
}
if (properties.actionDataChanged()) {
int index = changedProperties.indexOf("actionData");
if (index >= 0) {
QByteArray value = properties.getActionData();
QString changeHint = serializedDynamicsToDebugString(value);
changedProperties[index] = QString("actionData:") + changeHint;
}
}
if (properties.collisionlessChanged()) {
int index = changedProperties.indexOf("collisionless");
if (index >= 0) {
bool value = properties.getCollisionless();
QString changeHint = "0";
if (value) {
changeHint = "1";
}
changedProperties[index] = QString("collisionless:") + changeHint;
}
}
if (properties.dynamicChanged()) {
int index = changedProperties.indexOf("dynamic");
if (index >= 0) {
bool value = properties.getDynamic();
QString changeHint = "0";
if (value) {
changeHint = "1";
}
changedProperties[index] = QString("dynamic:") + changeHint;
}
}
if (properties.lockedChanged()) {
int index = changedProperties.indexOf("locked");
if (index >= 0) {
bool value = properties.getLocked();
QString changeHint = "0";
if (value) {
changeHint = "1";
}
changedProperties[index] = QString("locked:") + changeHint;
}
}
if (properties.userDataChanged()) {
int index = changedProperties.indexOf("userData");
if (index >= 0) {
QString changeHint = properties.getUserData();
changedProperties[index] = QString("userData:") + changeHint;
}
}
if (properties.parentJointIndexChanged()) {
int index = changedProperties.indexOf("parentJointIndex");
if (index >= 0) {
quint16 value = properties.getParentJointIndex();
changedProperties[index] = QString("parentJointIndex:") + QString::number((int)value);
}
}
if (properties.parentIDChanged()) {
int index = changedProperties.indexOf("parentID");
if (index >= 0) {
QUuid value = properties.getParentID();
changedProperties[index] = QString("parentID:") + value.toString();
}
}
if (properties.jointRotationsSetChanged()) {
int index = changedProperties.indexOf("jointRotationsSet");
if (index >= 0) {
auto value = properties.getJointRotationsSet().size();
changedProperties[index] = QString("jointRotationsSet:") + QString::number((int)value);
}
}
if (properties.jointRotationsChanged()) {
int index = changedProperties.indexOf("jointRotations");
if (index >= 0) {
auto value = properties.getJointRotations().size();
changedProperties[index] = QString("jointRotations:") + QString::number((int)value);
}
}
if (properties.jointTranslationsSetChanged()) {
int index = changedProperties.indexOf("jointTranslationsSet");
if (index >= 0) {
auto value = properties.getJointTranslationsSet().size();
changedProperties[index] = QString("jointTranslationsSet:") + QString::number((int)value);
}
}
if (properties.jointTranslationsChanged()) {
int index = changedProperties.indexOf("jointTranslations");
if (index >= 0) {
auto value = properties.getJointTranslations().size();
changedProperties[index] = QString("jointTranslations:") + QString::number((int)value);
}
}
if (properties.queryAACubeChanged()) {
int index = changedProperties.indexOf("queryAACube");
glm::vec3 center = properties.getQueryAACube().calcCenter();
changedProperties[index] = QString("queryAACube:") +
QString::number((int)center.x) + "," +
QString::number((int)center.y) + "," +
QString::number((int)center.z) + "/" +
QString::number(properties.getQueryAACube().getDimensions().x);
}
if (properties.positionChanged()) {
int index = changedProperties.indexOf("position");
glm::vec3 pos = properties.getPosition();
changedProperties[index] = QString("position:") +
QString::number((int)pos.x) + "," +
QString::number((int)pos.y) + "," +
QString::number((int)pos.z);
}
if (properties.lifetimeChanged()) {
int index = changedProperties.indexOf("lifetime");
if (index >= 0) {
float value = properties.getLifetime();
changedProperties[index] = QString("lifetime:") + QString::number((int)value);
}
}
}
bool EntityTree::filterProperties(EntityItemPointer& existingEntity, EntityItemProperties& propertiesIn, EntityItemProperties& propertiesOut, bool& wasChanged, FilterType filterType) {
bool accepted = true;
auto entityEditFilters = DependencyManager::get<EntityEditFilters>();
if (entityEditFilters) {
auto position = existingEntity ? existingEntity->getWorldPosition() : propertiesIn.getPosition();
auto entityID = existingEntity ? existingEntity->getEntityItemID() : EntityItemID();
accepted = entityEditFilters->filter(position, propertiesIn, propertiesOut, wasChanged, filterType, entityID, existingEntity);
}
return accepted;
}
void EntityTree::bumpTimestamp(EntityItemProperties& properties) { //fixme put class/header
const quint64 LAST_EDITED_SERVERSIDE_BUMP = 1; // usec
// also bump up the lastEdited time of the properties so that the interface that created this edit
// will accept our adjustment to lifetime back into its own entity-tree.
if (properties.getLastEdited() == UNKNOWN_CREATED_TIME) {
properties.setLastEdited(usecTimestampNow());
}
properties.setLastEdited(properties.getLastEdited() + LAST_EDITED_SERVERSIDE_BUMP);
}
bool EntityTree::isScriptInWhitelist(const QString& scriptProperty) {
// grab a URL representation of the entity script so we can check the host for this script
auto entityScriptURL = QUrl::fromUserInput(scriptProperty);
for (const auto& whiteListedPrefix : _entityScriptSourceWhitelist) {
auto whiteListURL = QUrl::fromUserInput(whiteListedPrefix);
// check if this script URL matches the whitelist domain and, optionally, is beneath the path
if (entityScriptURL.host().compare(whiteListURL.host(), Qt::CaseInsensitive) == 0 &&
entityScriptURL.path().startsWith(whiteListURL.path(), Qt::CaseInsensitive)) {
return true;
}
}
return false;
}
void EntityTree::startChallengeOwnershipTimer(const EntityItemID& entityItemID) {
QTimer* _challengeOwnershipTimeoutTimer = new QTimer(this);
connect(this, &EntityTree::killChallengeOwnershipTimeoutTimer, this, [=](const QString& certID) {
QReadLocker locker(&_entityCertificateIDMapLock);
EntityItemID id = _entityCertificateIDMap.value(certID);
if (entityItemID == id && _challengeOwnershipTimeoutTimer) {
_challengeOwnershipTimeoutTimer->stop();
_challengeOwnershipTimeoutTimer->deleteLater();
}
});
connect(_challengeOwnershipTimeoutTimer, &QTimer::timeout, this, [=]() {
qCDebug(entities) << "Ownership challenge timed out, deleting entity" << entityItemID;
withWriteLock([&] {
deleteEntity(entityItemID, true);
});
if (_challengeOwnershipTimeoutTimer) {
_challengeOwnershipTimeoutTimer->stop();
_challengeOwnershipTimeoutTimer->deleteLater();
}
});
_challengeOwnershipTimeoutTimer->setSingleShot(true);
_challengeOwnershipTimeoutTimer->start(5000);
}
QByteArray EntityTree::computeNonce(const QString& certID, const QString ownerKey) {
QUuid nonce = QUuid::createUuid(); //random, 5-hex value, separated by "-"
QByteArray nonceBytes = nonce.toByteArray();
QWriteLocker locker(&_certNonceMapLock);
_certNonceMap.insert(certID, QPair<QUuid, QString>(nonce, ownerKey));
return nonceBytes;
}
bool EntityTree::verifyNonce(const QString& certID, const QString& nonce, EntityItemID& id) {
{
QReadLocker certIdMapLocker(&_entityCertificateIDMapLock);
id = _entityCertificateIDMap.value(certID);
}
QString actualNonce, key;
{
QWriteLocker locker(&_certNonceMapLock);
QPair<QUuid, QString> sent = _certNonceMap.take(certID);
actualNonce = sent.first.toString();
key = sent.second;
}
QString annotatedKey = "-----BEGIN PUBLIC KEY-----\n" + key.insert(64, "\n") + "\n-----END PUBLIC KEY-----\n";
QByteArray hashedActualNonce = QCryptographicHash::hash(QByteArray(actualNonce.toUtf8()), QCryptographicHash::Sha256);
bool verificationSuccess = EntityItemProperties::verifySignature(annotatedKey.toUtf8(), hashedActualNonce, QByteArray::fromBase64(nonce.toUtf8()));
if (verificationSuccess) {
qCDebug(entities) << "Ownership challenge for Cert ID" << certID << "succeeded.";
} else {
qCDebug(entities) << "Ownership challenge for Cert ID" << certID << "failed. Actual nonce:" << actualNonce <<
"\nHashed actual nonce (digest):" << hashedActualNonce << "\nSent nonce (signature)" << nonce << "\nKey" << key;
}
return verificationSuccess;
}
void EntityTree::processChallengeOwnershipRequestPacket(ReceivedMessage& message, const SharedNodePointer& sourceNode) {
int certIDByteArraySize;
int textByteArraySize;
int nodeToChallengeByteArraySize;
message.readPrimitive(&certIDByteArraySize);
message.readPrimitive(&textByteArraySize);
message.readPrimitive(&nodeToChallengeByteArraySize);
QByteArray certID(message.read(certIDByteArraySize));
QByteArray text(message.read(textByteArraySize));
QByteArray nodeToChallenge(message.read(nodeToChallengeByteArraySize));
sendChallengeOwnershipRequestPacket(certID, text, nodeToChallenge, sourceNode);
}
void EntityTree::processChallengeOwnershipReplyPacket(ReceivedMessage& message, const SharedNodePointer& sourceNode) {
auto nodeList = DependencyManager::get<NodeList>();
int certIDByteArraySize;
int textByteArraySize;
int challengingNodeUUIDByteArraySize;
message.readPrimitive(&certIDByteArraySize);
message.readPrimitive(&textByteArraySize);
message.readPrimitive(&challengingNodeUUIDByteArraySize);
QByteArray certID(message.read(certIDByteArraySize));
QByteArray text(message.read(textByteArraySize));
QUuid challengingNode = QUuid::fromRfc4122(message.read(challengingNodeUUIDByteArraySize));
auto challengeOwnershipReplyPacket = NLPacket::create(PacketType::ChallengeOwnershipReply,
certIDByteArraySize + text.length() + 2 * sizeof(int),
true);
challengeOwnershipReplyPacket->writePrimitive(certIDByteArraySize);
challengeOwnershipReplyPacket->writePrimitive(text.length());
challengeOwnershipReplyPacket->write(certID);
challengeOwnershipReplyPacket->write(text);
nodeList->sendPacket(std::move(challengeOwnershipReplyPacket), *(nodeList->nodeWithUUID(challengingNode)));
}
void EntityTree::sendChallengeOwnershipPacket(const QString& certID, const QString& ownerKey, const EntityItemID& entityItemID, const SharedNodePointer& senderNode) {
// 1. Obtain a nonce
auto nodeList = DependencyManager::get<NodeList>();
QByteArray text = computeNonce(certID, ownerKey);
if (text == "") {
qCDebug(entities) << "CRITICAL ERROR: Couldn't compute nonce. Deleting entity...";
withWriteLock([&] {
deleteEntity(entityItemID, true);
});
} else {
qCDebug(entities) << "Challenging ownership of Cert ID" << certID;
// 2. Send the nonce to the rezzing avatar's node
QByteArray certIDByteArray = certID.toUtf8();
int certIDByteArraySize = certIDByteArray.size();
auto challengeOwnershipPacket = NLPacket::create(PacketType::ChallengeOwnership,
certIDByteArraySize + text.length() + 2 * sizeof(int),
true);
challengeOwnershipPacket->writePrimitive(certIDByteArraySize);
challengeOwnershipPacket->writePrimitive(text.length());
challengeOwnershipPacket->write(certIDByteArray);
challengeOwnershipPacket->write(text);
nodeList->sendPacket(std::move(challengeOwnershipPacket), *senderNode);
// 3. Kickoff a 10-second timeout timer that deletes the entity if we don't get an ownership response in time
if (thread() != QThread::currentThread()) {
QMetaObject::invokeMethod(this, "startChallengeOwnershipTimer", Q_ARG(const EntityItemID&, entityItemID));
return;
} else {
startChallengeOwnershipTimer(entityItemID);
}
}
}
void EntityTree::sendChallengeOwnershipRequestPacket(const QByteArray& certID, const QByteArray& text, const QByteArray& nodeToChallenge, const SharedNodePointer& senderNode) {
auto nodeList = DependencyManager::get<NodeList>();
// In this case, Client A is challenging Client B. Client A is inspecting a certified entity that it wants
// to make sure belongs to Avatar B.
QByteArray senderNodeUUID = senderNode->getUUID().toRfc4122();
int certIDByteArraySize = certID.length();
int TextByteArraySize = text.length();
int senderNodeUUIDSize = senderNodeUUID.length();
auto challengeOwnershipPacket = NLPacket::create(PacketType::ChallengeOwnershipRequest,
certIDByteArraySize + TextByteArraySize + senderNodeUUIDSize + 3 * sizeof(int),
true);
challengeOwnershipPacket->writePrimitive(certIDByteArraySize);
challengeOwnershipPacket->writePrimitive(TextByteArraySize);
challengeOwnershipPacket->writePrimitive(senderNodeUUIDSize);
challengeOwnershipPacket->write(certID);
challengeOwnershipPacket->write(text);
challengeOwnershipPacket->write(senderNodeUUID);
nodeList->sendPacket(std::move(challengeOwnershipPacket), *(nodeList->nodeWithUUID(QUuid::fromRfc4122(nodeToChallenge))));
}
void EntityTree::validatePop(const QString& certID, const EntityItemID& entityItemID, const SharedNodePointer& senderNode) {
// Start owner verification.
auto nodeList = DependencyManager::get<NodeList>();
// First, asynchronously hit "proof_of_purchase_status?transaction_type=transfer" endpoint.
QNetworkAccessManager& networkAccessManager = NetworkAccessManager::getInstance();
QNetworkRequest networkRequest;
networkRequest.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QUrl requestURL = NetworkingConstants::METAVERSE_SERVER_URL();
requestURL.setPath("/api/v1/commerce/proof_of_purchase_status/transfer");
QJsonObject request;
request["certificate_id"] = certID;
networkRequest.setUrl(requestURL);
QNetworkReply* networkReply = networkAccessManager.put(networkRequest, QJsonDocument(request).toJson());
connect(networkReply, &QNetworkReply::finished, [this, networkReply, entityItemID, certID, senderNode]() {
QJsonObject jsonObject = QJsonDocument::fromJson(networkReply->readAll()).object();
jsonObject = jsonObject["data"].toObject();
if (networkReply->error() == QNetworkReply::NoError) {
if (!jsonObject["invalid_reason"].toString().isEmpty()) {
qCDebug(entities) << "invalid_reason not empty, deleting entity" << entityItemID;
withWriteLock([&] {
deleteEntity(entityItemID, true);
});
} else if (jsonObject["transfer_status"].toArray().first().toString() == "failed") {
qCDebug(entities) << "'transfer_status' is 'failed', deleting entity" << entityItemID;
withWriteLock([&] {
deleteEntity(entityItemID, true);
});
} else {
// Second, challenge ownership of the PoP cert
// (ignore pending status; a failure will be cleaned up during DDV)
sendChallengeOwnershipPacket(certID,
jsonObject["transfer_recipient_key"].toString(),
entityItemID,
senderNode);
}
} else {
qCDebug(entities) << "Call to" << networkReply->url() << "failed with error" << networkReply->error() << "; deleting entity" << entityItemID
<< "More info:" << jsonObject;
withWriteLock([&] {
deleteEntity(entityItemID, true);
});
}
networkReply->deleteLater();
});
}
void EntityTree::processChallengeOwnershipPacket(ReceivedMessage& message, const SharedNodePointer& sourceNode) {
int certIDByteArraySize;
int textByteArraySize;
message.readPrimitive(&certIDByteArraySize);
message.readPrimitive(&textByteArraySize);
QString certID(message.read(certIDByteArraySize));
QString text(message.read(textByteArraySize));
emit killChallengeOwnershipTimeoutTimer(certID);
EntityItemID id;
if (!verifyNonce(certID, text, id)) {
if (!id.isNull()) {
deleteEntity(id, true);
}
}
}
int EntityTree::processEditPacketData(ReceivedMessage& message, const unsigned char* editData, int maxLength,
const SharedNodePointer& senderNode) {
if (!getIsServer()) {
qCWarning(entities) << "EntityTree::processEditPacketData() should only be called on a server tree.";
return 0;
}
int processedBytes = 0;
bool isAdd = false;
bool isClone = false;
// we handle these types of "edit" packets
switch (message.getType()) {
case PacketType::EntityErase: {
QByteArray dataByteArray = QByteArray::fromRawData(reinterpret_cast<const char*>(editData), maxLength);
processedBytes = processEraseMessageDetails(dataByteArray, senderNode);
break;
}
case PacketType::EntityClone:
isClone = true; // fall through to next case
// FALLTHRU
case PacketType::EntityAdd:
isAdd = true; // fall through to next case
// FALLTHRU
case PacketType::EntityPhysics:
case PacketType::EntityEdit: {
quint64 startDecode = 0, endDecode = 0;
quint64 startLookup = 0, endLookup = 0;
quint64 startUpdate = 0, endUpdate = 0;
quint64 startCreate = 0, endCreate = 0;
quint64 startFilter = 0, endFilter = 0;
quint64 startLogging = 0, endLogging = 0;
bool suppressDisallowedClientScript = false;
bool suppressDisallowedServerScript = false;
bool isPhysics = message.getType() == PacketType::EntityPhysics;
_totalEditMessages++;
EntityItemID entityItemID;
EntityItemProperties properties;
startDecode = usecTimestampNow();
bool validEditPacket = false;
EntityItemID entityIDToClone;
EntityItemPointer entityToClone;
if (isClone) {
QByteArray buffer = QByteArray::fromRawData(reinterpret_cast<const char*>(editData), maxLength);
validEditPacket = EntityItemProperties::decodeCloneEntityMessage(buffer, processedBytes, entityIDToClone, entityItemID);
if (validEditPacket) {
entityToClone = findEntityByEntityItemID(entityIDToClone);
if (entityToClone) {
properties = entityToClone->getProperties();
}
}
} else {
validEditPacket = EntityItemProperties::decodeEntityEditPacket(editData, maxLength, processedBytes, entityItemID, properties);
}
endDecode = usecTimestampNow();
EntityItemPointer existingEntity;
if (!isAdd) {
// search for the entity by EntityItemID
startLookup = usecTimestampNow();
existingEntity = findEntityByEntityItemID(entityItemID);
endLookup = usecTimestampNow();
if (!existingEntity) {
// this is not an add-entity operation, and we don't know about the identified entity.
validEditPacket = false;
}
}
if (validEditPacket && !_entityScriptSourceWhitelist.isEmpty()) {
bool wasDeletedBecauseOfClientScript = false;
// check the client entity script to make sure its URL is in the whitelist
if (!properties.getScript().isEmpty()) {
bool clientScriptPassedWhitelist = isScriptInWhitelist(properties.getScript());
if (!clientScriptPassedWhitelist) {
if (wantEditLogging()) {
qCDebug(entities) << "User [" << senderNode->getUUID()
<< "] attempting to set entity script not on whitelist, edit rejected";
}
// If this was an add, we also want to tell the client that sent this edit that the entity was not added.
if (isAdd) {
QWriteLocker locker(&_recentlyDeletedEntitiesLock);
_recentlyDeletedEntityItemIDs.insert(usecTimestampNow(), entityItemID);
validEditPacket = false;
wasDeletedBecauseOfClientScript = true;
} else {
suppressDisallowedClientScript = true;
}
}
}
// check all server entity scripts to make sure their URLs are in the whitelist
if (!properties.getServerScripts().isEmpty()) {
bool serverScriptPassedWhitelist = isScriptInWhitelist(properties.getServerScripts());
if (!serverScriptPassedWhitelist) {
if (wantEditLogging()) {
qCDebug(entities) << "User [" << senderNode->getUUID()
<< "] attempting to set server entity script not on whitelist, edit rejected";
}
// If this was an add, we also want to tell the client that sent this edit that the entity was not added.
if (isAdd) {
// Make sure we didn't already need to send back a delete because the client script failed
// the whitelist check
if (!wasDeletedBecauseOfClientScript) {
QWriteLocker locker(&_recentlyDeletedEntitiesLock);
_recentlyDeletedEntityItemIDs.insert(usecTimestampNow(), entityItemID);
validEditPacket = false;
}
} else {
suppressDisallowedServerScript = true;
}
}
}
}
if (!isClone) {
if ((isAdd || properties.lifetimeChanged()) &&
((!senderNode->getCanRez() && senderNode->getCanRezTmp()) ||
(!senderNode->getCanRezCertified() && senderNode->getCanRezTmpCertified()))) {
// this node is only allowed to rez temporary entities. if need be, cap the lifetime.
if (properties.getLifetime() == ENTITY_ITEM_IMMORTAL_LIFETIME ||
properties.getLifetime() > _maxTmpEntityLifetime) {
properties.setLifetime(_maxTmpEntityLifetime);
bumpTimestamp(properties);
}
}
if (isAdd && properties.getLocked() && !senderNode->isAllowedEditor()) {
// if a node can't change locks, don't allow it to create an already-locked entity -- automatically
// clear the locked property and allow the unlocked entity to be created.
properties.setLocked(false);
bumpTimestamp(properties);
}
}
// If we got a valid edit packet, then it could be a new entity or it could be an update to
// an existing entity... handle appropriately
if (validEditPacket) {
startFilter = usecTimestampNow();
bool wasChanged = false;
// Having (un)lock rights bypasses the filter, unless it's a physics result.
FilterType filterType = isPhysics ? FilterType::Physics : (isAdd ? FilterType::Add : FilterType::Edit);
bool allowed = (!isPhysics && senderNode->isAllowedEditor()) || filterProperties(existingEntity, properties, properties, wasChanged, filterType);
if (!allowed) {
auto timestamp = properties.getLastEdited();
properties = EntityItemProperties();
properties.setLastEdited(timestamp);
}
if (!allowed || wasChanged) {
bumpTimestamp(properties);
// For now, free ownership on any modification.
properties.clearSimulationOwner();
}
endFilter = usecTimestampNow();
if (existingEntity && !isAdd) {
if (suppressDisallowedClientScript) {
bumpTimestamp(properties);
properties.setScript(existingEntity->getScript());
}
if (suppressDisallowedServerScript) {
bumpTimestamp(properties);
properties.setServerScripts(existingEntity->getServerScripts());
}
// if the EntityItem exists, then update it
startLogging = usecTimestampNow();
if (wantEditLogging()) {
qCDebug(entities) << "User [" << senderNode->getUUID() << "] editing entity. ID:" << entityItemID;
qCDebug(entities) << " properties:" << properties;
}
if (wantTerseEditLogging()) {
QList<QString> changedProperties = properties.listChangedProperties();
fixupTerseEditLogging(properties, changedProperties);
qCDebug(entities) << senderNode->getUUID() << "edit" <<
existingEntity->getDebugName() << changedProperties;
}
endLogging = usecTimestampNow();
startUpdate = usecTimestampNow();
if (!isPhysics) {
properties.setLastEditedBy(senderNode->getUUID());
}
updateEntity(existingEntity, properties, senderNode);
existingEntity->markAsChangedOnServer();
endUpdate = usecTimestampNow();
_totalUpdates++;
} else if (isAdd) {
bool failedAdd = !allowed;
bool isCertified = !properties.getCertificateID().isEmpty();
bool isCloneable = properties.getCloneable();
int cloneLimit = properties.getCloneLimit();
if (!allowed) {
qCDebug(entities) << "Filtered entity add. ID:" << entityItemID;
} else if (!isClone && !isCertified && !senderNode->getCanRez() && !senderNode->getCanRezTmp()) {
failedAdd = true;
qCDebug(entities) << "User without 'uncertified rez rights' [" << senderNode->getUUID()
<< "] attempted to add an uncertified entity with ID:" << entityItemID;
} else if (!isClone && isCertified && !senderNode->getCanRezCertified() && !senderNode->getCanRezTmpCertified()) {
failedAdd = true;
qCDebug(entities) << "User without 'certified rez rights' [" << senderNode->getUUID()
<< "] attempted to add a certified entity with ID:" << entityItemID;
} else if (isClone && isCertified) {
failedAdd = true;
qCDebug(entities) << "User attempted to clone certified entity from entity ID:" << entityIDToClone;
} else if (isClone && !isCloneable) {
failedAdd = true;
qCDebug(entities) << "User attempted to clone non-cloneable entity from entity ID:" << entityIDToClone;
} else if (isClone && entityToClone && entityToClone->getCloneIDs().size() >= cloneLimit && cloneLimit != 0) {
failedAdd = true;
qCDebug(entities) << "User attempted to clone entity ID:" << entityIDToClone << " which reached it's cloneable limit.";
} else {
if (isClone) {
properties.convertToCloneProperties(entityIDToClone);
}
// this is a new entity... assign a new entityID
properties.setLastEditedBy(senderNode->getUUID());
startCreate = usecTimestampNow();
EntityItemPointer newEntity = addEntity(entityItemID, properties);
endCreate = usecTimestampNow();
_totalCreates++;
if (newEntity && isCertified && getIsServer()) {
if (!properties.verifyStaticCertificateProperties()) {
qCDebug(entities) << "User" << senderNode->getUUID()
<< "attempted to add a certified entity with ID" << entityItemID << "which failed"
<< "static certificate verification.";
// Delete the entity we just added if it doesn't pass static certificate verification
deleteEntity(entityItemID, true);
} else {
validatePop(properties.getCertificateID(), entityItemID, senderNode);
}
}
if (newEntity && isClone) {
entityToClone->addCloneID(newEntity->getEntityItemID());
newEntity->setCloneOriginID(entityIDToClone);
}
if (newEntity) {
newEntity->markAsChangedOnServer();
notifyNewlyCreatedEntity(*newEntity, senderNode);
startLogging = usecTimestampNow();
if (wantEditLogging()) {
qCDebug(entities) << "User [" << senderNode->getUUID() << "] added entity. ID:"
<< newEntity->getEntityItemID();
qCDebug(entities) << " properties:" << properties;
}
if (wantTerseEditLogging()) {
QList<QString> changedProperties = properties.listChangedProperties();
fixupTerseEditLogging(properties, changedProperties);
qCDebug(entities) << senderNode->getUUID() << "add" << entityItemID << changedProperties;
}
endLogging = usecTimestampNow();
} else {
failedAdd = true;
qCDebug(entities) << "Add entity failed ID:" << entityItemID;
}
}
if (failedAdd) { // Let client know it failed, so that they don't have an entity that no one else sees.
QWriteLocker locker(&_recentlyDeletedEntitiesLock);
_recentlyDeletedEntityItemIDs.insert(usecTimestampNow(), entityItemID);
}
} else {
HIFI_FCDEBUG(entities(), "Edit failed. [" << message.getType() <<"] " <<
"entity id:" << entityItemID <<
"existingEntity pointer:" << existingEntity.get());
}
}
_totalDecodeTime += endDecode - startDecode;
_totalLookupTime += endLookup - startLookup;
_totalUpdateTime += endUpdate - startUpdate;
_totalCreateTime += endCreate - startCreate;
_totalLoggingTime += endLogging - startLogging;
_totalFilterTime += endFilter - startFilter;
break;
}
default:
processedBytes = 0;
break;
}
return processedBytes;
}
void EntityTree::notifyNewlyCreatedEntity(const EntityItem& newEntity, const SharedNodePointer& senderNode) {
_newlyCreatedHooksLock.lockForRead();
for (int i = 0; i < _newlyCreatedHooks.size(); i++) {
_newlyCreatedHooks[i]->entityCreated(newEntity, senderNode);
}
_newlyCreatedHooksLock.unlock();
}
void EntityTree::addNewlyCreatedHook(NewlyCreatedEntityHook* hook) {
_newlyCreatedHooksLock.lockForWrite();
_newlyCreatedHooks.push_back(hook);
_newlyCreatedHooksLock.unlock();
}
void EntityTree::removeNewlyCreatedHook(NewlyCreatedEntityHook* hook) {
_newlyCreatedHooksLock.lockForWrite();
for (int i = 0; i < _newlyCreatedHooks.size(); i++) {
if (_newlyCreatedHooks[i] == hook) {
_newlyCreatedHooks.erase(_newlyCreatedHooks.begin() + i);
break;
}
}
_newlyCreatedHooksLock.unlock();
}
void EntityTree::releaseSceneEncodeData(OctreeElementExtraEncodeData* extraEncodeData) const {
extraEncodeData->clear();
}
void EntityTree::entityChanged(EntityItemPointer entity) {
if (entity->isSimulated()) {
_simulation->changeEntity(entity);
}
}
void EntityTree::fixupNeedsParentFixups() {
PROFILE_RANGE(simulation_physics, "FixupParents");
MovingEntitiesOperator moveOperator;
QVector<EntityItemWeakPointer> entitiesToFixup;
{
QWriteLocker locker(&_needsParentFixupLock);
entitiesToFixup = _needsParentFixup;
_needsParentFixup.clear();
}
QMutableVectorIterator<EntityItemWeakPointer> iter(entitiesToFixup);
while (iter.hasNext()) {
EntityItemWeakPointer entityWP = iter.next();
EntityItemPointer entity = entityWP.lock();
if (!entity) {
// entity was deleted before we found its parent
iter.remove();
continue;
}
entity->requiresRecalcBoxes();
bool queryAACubeSuccess { false };
bool maxAACubeSuccess { false };
AACube newCube = entity->getQueryAACube(queryAACubeSuccess);
if (queryAACubeSuccess) {
// make sure queryAACube encompasses maxAACube
AACube maxAACube = entity->getMaximumAACube(maxAACubeSuccess);
if (maxAACubeSuccess && !newCube.contains(maxAACube)) {
newCube = maxAACube;
}
}
bool doMove = false;
if (entity->isParentIDValid() && maxAACubeSuccess) { // maxAACubeSuccess of true means all ancestors are known
iter.remove(); // this entity is all hooked up; we can remove it from the list
// this entity's parent was previously not known, and now is. Update its location in the EntityTree...
doMove = true;
// the bounds on the render-item may need to be updated, the rigid body in the physics engine may
// need to be moved.
entity->markDirtyFlags(Simulation::DIRTY_MOTION_TYPE |
Simulation::DIRTY_COLLISION_GROUP |
Simulation::DIRTY_TRANSFORM);
entityChanged(entity);
entity->locationChanged(true, false);
entity->forEachDescendant([&](SpatiallyNestablePointer object) {
if (object->getNestableType() == NestableType::Entity) {
EntityItemPointer descendantEntity = std::static_pointer_cast<EntityItem>(object);
descendantEntity->markDirtyFlags(Simulation::DIRTY_MOTION_TYPE |
Simulation::DIRTY_COLLISION_GROUP |
Simulation::DIRTY_TRANSFORM);
entityChanged(descendantEntity);
}
object->locationChanged(true, false);
});
// Update our parent's bounding box
bool success = false;
auto parent = entity->getParentPointer(success);
if (success && parent) {
parent->updateQueryAACube();
}
entity->postParentFixup();
} else if (getIsServer() || _avatarIDs.contains(entity->getParentID())) {
// this is a child of an avatar, which the entity server will never have
// a SpatiallyNestable object for. Add it to a list for cleanup when the avatar leaves.
if (!_childrenOfAvatars.contains(entity->getParentID())) {
_childrenOfAvatars[entity->getParentID()] = QSet<EntityItemID>();
}
_childrenOfAvatars[entity->getParentID()] += entity->getEntityItemID();
doMove = true;
iter.remove(); // and pull it out of the list
}
if (queryAACubeSuccess && doMove) {
moveOperator.addEntityToMoveList(entity, newCube);
}
}
if (moveOperator.hasMovingEntities()) {
PerformanceTimer perfTimer("recurseTreeWithOperator");
recurseTreeWithOperator(&moveOperator);
}
{
QWriteLocker locker(&_needsParentFixupLock);
// add back the entities that did not get fixup
_needsParentFixup.append(entitiesToFixup);
}
}
void EntityTree::deleteDescendantsOfAvatar(QUuid avatarID) {
if (_childrenOfAvatars.contains(avatarID)) {
deleteEntities(_childrenOfAvatars[avatarID]);
_childrenOfAvatars.remove(avatarID);
}
}
void EntityTree::removeFromChildrenOfAvatars(EntityItemPointer entity) {
QUuid avatarID = entity->getParentID();
if (_childrenOfAvatars.contains(avatarID)) {
_childrenOfAvatars[avatarID].remove(entity->getID());
}
}
void EntityTree::addToNeedsParentFixupList(EntityItemPointer entity) {
QWriteLocker locker(&_needsParentFixupLock);
_needsParentFixup.append(entity);
}
void EntityTree::update(bool simulate) {
PROFILE_RANGE(simulation_physics, "UpdateTree");
PerformanceTimer perfTimer("updateTree");
withWriteLock([&] {
fixupNeedsParentFixups();
if (simulate && _simulation) {
_simulation->updateEntities();
{
PROFILE_RANGE(simulation_physics, "Deletes");
SetOfEntities deadEntities;
_simulation->takeDeadEntities(deadEntities);
if (!deadEntities.empty()) {
// translate into list of ID's
QSet<EntityItemID> idsToDelete;
for (auto entity : deadEntities) {
idsToDelete.insert(entity->getEntityItemID());
}
// delete these things the roundabout way
deleteEntities(idsToDelete, true);
}
}
}
});
}
quint64 EntityTree::getAdjustedConsiderSince(quint64 sinceTime) {
return (sinceTime - DELETED_ENTITIES_EXTRA_USECS_TO_CONSIDER);
}
bool EntityTree::hasEntitiesDeletedSince(quint64 sinceTime) {
quint64 considerEntitiesSince = getAdjustedConsiderSince(sinceTime);
// we can probably leverage the ordered nature of QMultiMap to do this quickly...
bool hasSomethingNewer = false;
QReadLocker locker(&_recentlyDeletedEntitiesLock);
QMultiMap<quint64, QUuid>::const_iterator iterator = _recentlyDeletedEntityItemIDs.constBegin();
while (iterator != _recentlyDeletedEntityItemIDs.constEnd()) {
if (iterator.key() > considerEntitiesSince) {
hasSomethingNewer = true;
break; // if we have at least one item, we don't need to keep searching
}
++iterator;
}
#ifdef EXTRA_ERASE_DEBUGGING
if (hasSomethingNewer) {
int elapsed = usecTimestampNow() - considerEntitiesSince;
int difference = considerEntitiesSince - sinceTime;
qCDebug(entities) << "EntityTree::hasEntitiesDeletedSince() sinceTime:" << sinceTime
<< "considerEntitiesSince:" << considerEntitiesSince << "elapsed:" << elapsed << "difference:" << difference;
}
#endif
return hasSomethingNewer;
}
// called by the server when it knows all nodes have been sent deleted packets
void EntityTree::forgetEntitiesDeletedBefore(quint64 sinceTime) {
quint64 considerSinceTime = sinceTime - DELETED_ENTITIES_EXTRA_USECS_TO_CONSIDER;
QSet<quint64> keysToRemove;
QWriteLocker locker(&_recentlyDeletedEntitiesLock);
QMultiMap<quint64, QUuid>::iterator iterator = _recentlyDeletedEntityItemIDs.begin();
// First find all the keys in the map that are older and need to be deleted
while (iterator != _recentlyDeletedEntityItemIDs.end()) {
if (iterator.key() <= considerSinceTime) {
keysToRemove << iterator.key();
}
++iterator;
}
// Now run through the keysToRemove and remove them
foreach (quint64 value, keysToRemove) {
_recentlyDeletedEntityItemIDs.remove(value);
}
}
bool EntityTree::shouldEraseEntity(EntityItemID entityID, const SharedNodePointer& sourceNode) {
EntityItemPointer existingEntity;
auto startLookup = usecTimestampNow();
existingEntity = findEntityByEntityItemID(entityID);
auto endLookup = usecTimestampNow();
_totalLookupTime += endLookup - startLookup;
auto startFilter = usecTimestampNow();
FilterType filterType = FilterType::Delete;
EntityItemProperties dummyProperties;
bool wasChanged = false;
bool allowed = (sourceNode->isAllowedEditor()) || filterProperties(existingEntity, dummyProperties, dummyProperties, wasChanged, filterType);
auto endFilter = usecTimestampNow();
_totalFilterTime += endFilter - startFilter;
if (allowed) {
if (wantEditLogging() || wantTerseEditLogging()) {
qCDebug(entities) << "User [" << sourceNode->getUUID() << "] deleting entity. ID:" << entityID;
}
} else if (wantEditLogging() || wantTerseEditLogging()) {
qCDebug(entities) << "User [" << sourceNode->getUUID() << "] attempted to deleteentity. ID:" << entityID << " Filter rejected erase.";
}
return allowed;
}
// TODO: consider consolidating processEraseMessageDetails() and processEraseMessage()
int EntityTree::processEraseMessage(ReceivedMessage& message, const SharedNodePointer& sourceNode) {
#ifdef EXTRA_ERASE_DEBUGGING
qCDebug(entities) << "EntityTree::processEraseMessage()";
#endif
withWriteLock([&] {
message.seek(sizeof(OCTREE_PACKET_FLAGS) + sizeof(OCTREE_PACKET_SEQUENCE) + sizeof(OCTREE_PACKET_SENT_TIME));
uint16_t numberOfIDs = 0; // placeholder for now
message.readPrimitive(&numberOfIDs);
if (numberOfIDs > 0) {
QSet<EntityItemID> entityItemIDsToDelete;
for (size_t i = 0; i < numberOfIDs; i++) {
if (NUM_BYTES_RFC4122_UUID > message.getBytesLeftToRead()) {
qCDebug(entities) << "EntityTree::processEraseMessage().... bailing because not enough bytes in buffer";
break; // bail to prevent buffer overflow
}
QUuid entityID = QUuid::fromRfc4122(message.readWithoutCopy(NUM_BYTES_RFC4122_UUID));
#ifdef EXTRA_ERASE_DEBUGGING
qCDebug(entities) << " ---- EntityTree::processEraseMessage() contained ID:" << entityID;
#endif
EntityItemID entityItemID(entityID);
if (shouldEraseEntity(entityID, sourceNode)) {
entityItemIDsToDelete << entityItemID;
cleanupCloneIDs(entityItemID);
}
}
deleteEntities(entityItemIDsToDelete, true, true);
}
});
return message.getPosition();
}
// This version skips over the header
// NOTE: Caller must lock the tree before calling this.
// TODO: consider consolidating processEraseMessageDetails() and processEraseMessage()
int EntityTree::processEraseMessageDetails(const QByteArray& dataByteArray, const SharedNodePointer& sourceNode) {
#ifdef EXTRA_ERASE_DEBUGGING
qCDebug(entities) << "EntityTree::processEraseMessageDetails()";
#endif
const unsigned char* packetData = (const unsigned char*)dataByteArray.constData();
const unsigned char* dataAt = packetData;
size_t packetLength = dataByteArray.size();
size_t processedBytes = 0;
uint16_t numberOfIds = 0; // placeholder for now
memcpy(&numberOfIds, dataAt, sizeof(numberOfIds));
dataAt += sizeof(numberOfIds);
processedBytes += sizeof(numberOfIds);
if (numberOfIds > 0) {
QSet<EntityItemID> entityItemIDsToDelete;
for (size_t i = 0; i < numberOfIds; i++) {
if (processedBytes + NUM_BYTES_RFC4122_UUID > packetLength) {
qCDebug(entities) << "EntityTree::processEraseMessageDetails().... bailing because not enough bytes in buffer";
break; // bail to prevent buffer overflow
}
QByteArray encodedID = dataByteArray.mid((int)processedBytes, NUM_BYTES_RFC4122_UUID);
QUuid entityID = QUuid::fromRfc4122(encodedID);
dataAt += encodedID.size();
processedBytes += encodedID.size();
#ifdef EXTRA_ERASE_DEBUGGING
qCDebug(entities) << " ---- EntityTree::processEraseMessageDetails() contains id:" << entityID;
#endif
EntityItemID entityItemID(entityID);
if (shouldEraseEntity(entityID, sourceNode)) {
entityItemIDsToDelete << entityItemID;
cleanupCloneIDs(entityItemID);
}
}
deleteEntities(entityItemIDsToDelete, true, true);
}
return (int)processedBytes;
}
EntityTreeElementPointer EntityTree::getContainingElement(const EntityItemID& entityItemID) /*const*/ {
EntityItemPointer entity;
{
QReadLocker locker(&_entityMapLock);
entity = _entityMap.value(entityItemID);
}
if (entity) {
return entity->getElement();
}
return EntityTreeElementPointer(nullptr);
}
void EntityTree::addEntityMapEntry(EntityItemPointer entity) {
EntityItemID id = entity->getEntityItemID();
QWriteLocker locker(&_entityMapLock);
EntityItemPointer otherEntity = _entityMap.value(id);
if (otherEntity) {
qCWarning(entities) << "EntityTree::addEntityMapEntry() found pre-existing id " << id;
assert(false);
return;
}
_entityMap.insert(id, entity);
}
void EntityTree::clearEntityMapEntry(const EntityItemID& id) {
QWriteLocker locker(&_entityMapLock);
_entityMap.remove(id);
}
void EntityTree::debugDumpMap() {
// QHash's are implicitly shared, so we make a shared copy and use that instead.
// This way we might be able to avoid both a lock and a true copy.
QHash<EntityItemID, EntityItemPointer> localMap(_entityMap);
qCDebug(entities) << "EntityTree::debugDumpMap() --------------------------";
QHashIterator<EntityItemID, EntityItemPointer> i(localMap);
while (i.hasNext()) {
i.next();
qCDebug(entities) << i.key() << ": " << i.value()->getElement().get();
}
qCDebug(entities) << "-----------------------------------------------------";
}
class ContentsDimensionOperator : public RecurseOctreeOperator {
public:
virtual bool preRecursion(const OctreeElementPointer& element) override;
virtual bool postRecursion(const OctreeElementPointer& element) override { return true; }
glm::vec3 getDimensions() const { return _contentExtents.size(); }
float getLargestDimension() const { return _contentExtents.largestDimension(); }
private:
Extents _contentExtents;
};
bool ContentsDimensionOperator::preRecursion(const OctreeElementPointer& element) {
EntityTreeElementPointer entityTreeElement = std::static_pointer_cast<EntityTreeElement>(element);
entityTreeElement->expandExtentsToContents(_contentExtents);
return true;
}
glm::vec3 EntityTree::getContentsDimensions() {
ContentsDimensionOperator theOperator;
recurseTreeWithOperator(&theOperator);
return theOperator.getDimensions();
}
float EntityTree::getContentsLargestDimension() {
ContentsDimensionOperator theOperator;
recurseTreeWithOperator(&theOperator);
return theOperator.getLargestDimension();
}
class DebugOperator : public RecurseOctreeOperator {
public:
virtual bool preRecursion(const OctreeElementPointer& element) override;
virtual bool postRecursion(const OctreeElementPointer& element) override { return true; }
};
bool DebugOperator::preRecursion(const OctreeElementPointer& element) {
EntityTreeElementPointer entityTreeElement = std::static_pointer_cast<EntityTreeElement>(element);
qCDebug(entities) << "EntityTreeElement [" << entityTreeElement.get() << "]";
entityTreeElement->debugDump();
return true;
}
void EntityTree::dumpTree() {
DebugOperator theOperator;
recurseTreeWithOperator(&theOperator);
}
class PruneOperator : public RecurseOctreeOperator {
public:
virtual bool preRecursion(const OctreeElementPointer& element) override { return true; }
virtual bool postRecursion(const OctreeElementPointer& element) override;
};
bool PruneOperator::postRecursion(const OctreeElementPointer& element) {
EntityTreeElementPointer entityTreeElement = std::static_pointer_cast<EntityTreeElement>(element);
entityTreeElement->pruneChildren();
return true;
}
void EntityTree::pruneTree() {
PruneOperator theOperator;
recurseTreeWithOperator(&theOperator);
}
QByteArray EntityTree::remapActionDataIDs(QByteArray actionData, QHash<EntityItemID, EntityItemID>& map) {
if (actionData.isEmpty()) {
return actionData;
}
QDataStream serializedActionsStream(actionData);
QVector<QByteArray> serializedActions;
serializedActionsStream >> serializedActions;
auto actionFactory = DependencyManager::get<EntityDynamicFactoryInterface>();
QHash<QUuid, EntityDynamicPointer> remappedActions;
foreach(QByteArray serializedAction, serializedActions) {
QDataStream serializedActionStream(serializedAction);
EntityDynamicType actionType;
QUuid oldActionID;
serializedActionStream >> actionType;
serializedActionStream >> oldActionID;
EntityDynamicPointer action = actionFactory->factoryBA(nullptr, serializedAction);
if (action) {
action->remapIDs(map);
remappedActions[action->getID()] = action;
}
}
QVector<QByteArray> remappedSerializedActions;
QHash<QUuid, EntityDynamicPointer>::const_iterator i = remappedActions.begin();
while (i != remappedActions.end()) {
EntityDynamicPointer action = i.value();
QByteArray bytesForAction = action->serialize();
remappedSerializedActions << bytesForAction;
i++;
}
QByteArray result;
QDataStream remappedSerializedActionsStream(&result, QIODevice::WriteOnly);
remappedSerializedActionsStream << remappedSerializedActions;
return result;
}
QVector<EntityItemID> EntityTree::sendEntities(EntityEditPacketSender* packetSender, EntityTreePointer localTree,
float x, float y, float z) {
SendEntitiesOperationArgs args;
args.ourTree = this;
args.otherTree = localTree;
args.root = glm::vec3(x, y, z);
// If this is called repeatedly (e.g., multiple pastes with the same data), the new elements will clash unless we
// use new identifiers. We need to keep a map so that we can map parent identifiers correctly.
QHash<EntityItemID, EntityItemID> map;
args.map = ↦
withReadLock([&] {
recurseTreeWithOperation(sendEntitiesOperation, &args);
});
// The values from map are used as the list of successfully "sent" entities. If some didn't actually make it,
// pull them out. Bogus entries could happen if part of the imported data makes some reference to an entity
// that isn't in the data being imported. For those that made it, fix up their queryAACubes and send an
// add-entity packet to the server.
// fix the queryAACubes of any children that were read in before their parents, get them into the correct element
MovingEntitiesOperator moveOperator;
QHash<EntityItemID, EntityItemID>::iterator i = map.begin();
while (i != map.end()) {
EntityItemID newID = i.value();
EntityItemPointer entity = localTree->findEntityByEntityItemID(newID);
if (entity) {
if (!entity->getParentID().isNull()) {
addToNeedsParentFixupList(entity);
}
entity->forceQueryAACubeUpdate();
entity->updateQueryAACube();
moveOperator.addEntityToMoveList(entity, entity->getQueryAACube());
i++;
} else {
i = map.erase(i);
}
}
if (moveOperator.hasMovingEntities()) {
PerformanceTimer perfTimer("recurseTreeWithOperator");
localTree->recurseTreeWithOperator(&moveOperator);
}
if (!_serverlessDomain) {
// send add-entity packets to the server
i = map.begin();
while (i != map.end()) {
EntityItemID newID = i.value();
EntityItemPointer entity = localTree->findEntityByEntityItemID(newID);
if (entity) {
// queue the packet to send to the server
entity->updateQueryAACube();
EntityItemProperties properties = entity->getProperties();
properties.markAllChanged(); // so the entire property set is considered new, since we're making a new entity
packetSender->queueEditEntityMessage(PacketType::EntityAdd, localTree, newID, properties);
i++;
} else {
i = map.erase(i);
}
}
packetSender->releaseQueuedMessages();
}
return map.values().toVector();
}
bool EntityTree::sendEntitiesOperation(const OctreeElementPointer& element, void* extraData) {
SendEntitiesOperationArgs* args = static_cast<SendEntitiesOperationArgs*>(extraData);
EntityTreeElementPointer entityTreeElement = std::static_pointer_cast<EntityTreeElement>(element);
auto getMapped = [&args](EntityItemID oldID) {
if (oldID.isNull()) {
return EntityItemID();
}
QHash<EntityItemID, EntityItemID>::iterator iter = args->map->find(oldID);
if (iter == args->map->end()) {
EntityItemID newID;
if (oldID == AVATAR_SELF_ID) {
auto nodeList = DependencyManager::get<NodeList>();
newID = EntityItemID(nodeList->getSessionUUID());
} else {
newID = QUuid::createUuid();
}
args->map->insert(oldID, newID);
return newID;
}
return iter.value();
};
entityTreeElement->forEachEntity([&args, &getMapped, &element](EntityItemPointer item) {
EntityItemID oldID = item->getEntityItemID();
EntityItemID newID = getMapped(oldID);
EntityItemProperties properties = item->getProperties();
EntityItemID oldParentID = properties.getParentID();
if (oldParentID.isInvalidID()) { // no parent
properties.setPosition(properties.getPosition() + args->root);
} else {
EntityItemPointer parentEntity = args->ourTree->findEntityByEntityItemID(oldParentID);
if (parentEntity || oldParentID == AVATAR_SELF_ID) { // map the parent
properties.setParentID(getMapped(oldParentID));
// But do not add root offset in this case.
} else { // Should not happen, but let's try to be helpful...
item->globalizeProperties(properties, "Cannot find %3 parent of %2 %1", args->root);
}
}
properties.setXNNeighborID(getMapped(properties.getXNNeighborID()));
properties.setXPNeighborID(getMapped(properties.getXPNeighborID()));
properties.setYNNeighborID(getMapped(properties.getYNNeighborID()));
properties.setYPNeighborID(getMapped(properties.getYPNeighborID()));
properties.setZNNeighborID(getMapped(properties.getZNNeighborID()));
properties.setZPNeighborID(getMapped(properties.getZPNeighborID()));
QByteArray actionData = properties.getActionData();
properties.setActionData(remapActionDataIDs(actionData, *args->map));
// set creation time to "now" for imported entities
properties.setCreated(usecTimestampNow());
EntityTreeElementPointer entityTreeElement = std::static_pointer_cast<EntityTreeElement>(element);
EntityTreePointer tree = entityTreeElement->getTree();
// also update the local tree instantly (note: this is not our tree, but an alternate tree)
if (args->otherTree) {
args->otherTree->withWriteLock([&] {
EntityItemPointer entity = args->otherTree->addEntity(newID, properties);
if (entity) {
entity->deserializeActions();
}
// else: there was an error adding this entity
});
}
return newID;
});
return true;
}
bool EntityTree::writeToMap(QVariantMap& entityDescription, OctreeElementPointer element, bool skipDefaultValues,
bool skipThoseWithBadParents) {
if (! entityDescription.contains("Entities")) {
entityDescription["Entities"] = QVariantList();
}
entityDescription["DataVersion"] = _persistDataVersion;
entityDescription["Id"] = _persistID;
QScriptEngine scriptEngine;
RecurseOctreeToMapOperator theOperator(entityDescription, element, &scriptEngine, skipDefaultValues,
skipThoseWithBadParents, _myAvatar);
withReadLock([&] {
recurseTreeWithOperator(&theOperator);
});
return true;
}
void convertGrabUserDataToProperties(EntityItemProperties& properties) {
GrabPropertyGroup& grabProperties = properties.getGrab();
QJsonObject userData = QJsonDocument::fromJson(properties.getUserData().toUtf8()).object();
QJsonValue grabbableKeyValue = userData["grabbableKey"];
if (grabbableKeyValue.isObject()) {
QJsonObject grabbableKey = grabbableKeyValue.toObject();
QJsonValue wantsTrigger = grabbableKey["wantsTrigger"];
if (wantsTrigger.isBool()) {
grabProperties.setTriggerable(wantsTrigger.toBool());
}
QJsonValue triggerable = grabbableKey["triggerable"];
if (triggerable.isBool()) {
grabProperties.setTriggerable(triggerable.toBool());
}
QJsonValue grabbable = grabbableKey["grabbable"];
if (grabbable.isBool()) {
grabProperties.setGrabbable(grabbable.toBool());
}
QJsonValue ignoreIK = grabbableKey["ignoreIK"];
if (ignoreIK.isBool()) {
grabProperties.setGrabFollowsController(ignoreIK.toBool());
}
QJsonValue kinematic = grabbableKey["kinematic"];
if (kinematic.isBool()) {
grabProperties.setGrabKinematic(kinematic.toBool());
}
QJsonValue equippable = grabbableKey["equippable"];
if (equippable.isBool()) {
grabProperties.setEquippable(equippable.toBool());
}
grabProperties.setGrabDelegateToParent(true);
if (grabbableKey["spatialKey"].isObject()) {
QJsonObject spatialKey = grabbableKey["spatialKey"].toObject();
grabProperties.setEquippable(true);
if (spatialKey["leftRelativePosition"].isObject()) {
grabProperties.setEquippableLeftPosition(qMapToVec3(spatialKey["leftRelativePosition"].toVariant()));
}
if (spatialKey["rightRelativePosition"].isObject()) {
grabProperties.setEquippableRightPosition(qMapToVec3(spatialKey["rightRelativePosition"].toVariant()));
}
if (spatialKey["relativeRotation"].isObject()) {
grabProperties.setEquippableLeftRotation(qMapToQuat(spatialKey["relativeRotation"].toVariant()));
grabProperties.setEquippableRightRotation(qMapToQuat(spatialKey["relativeRotation"].toVariant()));
}
}
}
QJsonValue wearableValue = userData["wearable"];
if (wearableValue.isObject()) {
QJsonObject wearable = wearableValue.toObject();
QJsonObject joints = wearable["joints"].toObject();
if (joints["LeftHand"].isArray()) {
QJsonArray leftHand = joints["LeftHand"].toArray();
if (leftHand.size() == 2) {
grabProperties.setEquippable(true);
grabProperties.setEquippableLeftPosition(qMapToVec3(leftHand[0].toVariant()));
grabProperties.setEquippableLeftRotation(qMapToQuat(leftHand[1].toVariant()));
}
}
if (joints["RightHand"].isArray()) {
QJsonArray rightHand = joints["RightHand"].toArray();
if (rightHand.size() == 2) {
grabProperties.setEquippable(true);
grabProperties.setEquippableRightPosition(qMapToVec3(rightHand[0].toVariant()));
grabProperties.setEquippableRightRotation(qMapToQuat(rightHand[1].toVariant()));
}
}
}
QJsonValue equipHotspotsValue = userData["equipHotspots"];
if (equipHotspotsValue.isArray()) {
QJsonArray equipHotspots = equipHotspotsValue.toArray();
if (equipHotspots.size() > 0) {
// just take the first one
QJsonObject firstHotSpot = equipHotspots[0].toObject();
QJsonObject joints = firstHotSpot["joints"].toObject();
if (joints["LeftHand"].isArray()) {
QJsonArray leftHand = joints["LeftHand"].toArray();
if (leftHand.size() == 2) {
grabProperties.setEquippableLeftPosition(qMapToVec3(leftHand[0].toVariant()));
grabProperties.setEquippableLeftRotation(qMapToQuat(leftHand[1].toVariant()));
}
}
if (joints["RightHand"].isArray()) {
QJsonArray rightHand = joints["RightHand"].toArray();
if (rightHand.size() == 2) {
grabProperties.setEquippable(true);
grabProperties.setEquippableRightPosition(qMapToVec3(rightHand[0].toVariant()));
grabProperties.setEquippableRightRotation(qMapToQuat(rightHand[1].toVariant()));
}
}
QJsonValue indicatorURL = firstHotSpot["modelURL"];
if (indicatorURL.isString()) {
grabProperties.setEquippableIndicatorURL(indicatorURL.toString());
}
QJsonValue indicatorScale = firstHotSpot["modelScale"];
if (indicatorScale.isDouble()) {
grabProperties.setEquippableIndicatorScale(glm::vec3((float)indicatorScale.toDouble()));
} else if (indicatorScale.isObject()) {
grabProperties.setEquippableIndicatorScale(qMapToVec3(indicatorScale.toVariant()));
}
QJsonValue indicatorOffset = firstHotSpot["position"];
if (indicatorOffset.isObject()) {
grabProperties.setEquippableIndicatorOffset(qMapToVec3(indicatorOffset.toVariant()));
}
}
}
}
bool EntityTree::readFromMap(QVariantMap& map) {
// These are needed to deal with older content (before adding inheritance modes)
int contentVersion = map["Version"].toInt();
if (map.contains("Id")) {
_persistID = map["Id"].toUuid();
}
if (map.contains("DataVersion")) {
_persistDataVersion = map["DataVersion"].toInt();
}
_namedPaths.clear();
if (map.contains("Paths")) {
QVariantMap namedPathsMap = map["Paths"].toMap();
for(QVariantMap::const_iterator iter = namedPathsMap.begin(); iter != namedPathsMap.end(); ++iter) {
QString namedPathName = iter.key();
QString namedPathViewPoint = iter.value().toString();
_namedPaths[namedPathName] = namedPathViewPoint;
}
}
// map will have a top-level list keyed as "Entities". This will be extracted
// and iterated over. Each member of this list is converted to a QVariantMap, then
// to a QScriptValue, and then to EntityItemProperties. These properties are used
// to add the new entity to the EntityTree.
QVariantList entitiesQList = map["Entities"].toList();
QScriptEngine scriptEngine;
if (entitiesQList.length() == 0) {
// Empty map or invalidly formed file.
return false;
}
QMap<QUuid, QVector<QUuid>> cloneIDs;
bool success = true;
foreach (QVariant entityVariant, entitiesQList) {
// QVariantMap --> QScriptValue --> EntityItemProperties --> Entity
QVariantMap entityMap = entityVariant.toMap();
// handle parentJointName for wearables
if (_myAvatar && entityMap.contains("parentJointName") && entityMap.contains("parentID") &&
QUuid(entityMap["parentID"].toString()) == AVATAR_SELF_ID) {
entityMap["parentJointIndex"] = _myAvatar->getJointIndex(entityMap["parentJointName"].toString());
qCDebug(entities) << "Found parentJointName " << entityMap["parentJointName"].toString() <<
" mapped it to parentJointIndex " << entityMap["parentJointIndex"].toInt();
}
QScriptValue entityScriptValue = variantMapToScriptValue(entityMap, scriptEngine);
EntityItemProperties properties;
EntityItemPropertiesFromScriptValueIgnoreReadOnly(entityScriptValue, properties);
EntityItemID entityItemID;
if (entityMap.contains("id")) {
entityItemID = EntityItemID(QUuid(entityMap["id"].toString()));
} else {
entityItemID = EntityItemID(QUuid::createUuid());
}
// Convert old clientOnly bool to new entityHostType enum
// (must happen before setOwningAvatarID below)
if (contentVersion < (int)EntityVersion::EntityHostTypes) {
if (entityMap.contains("clientOnly")) {
properties.setEntityHostType(entityMap["clientOnly"].toBool() ? entity::HostType::AVATAR : entity::HostType::DOMAIN);
}
}
if (properties.getEntityHostType() == entity::HostType::AVATAR) {
auto nodeList = DependencyManager::get<NodeList>();
const QUuid myNodeID = nodeList->getSessionUUID();
properties.setOwningAvatarID(myNodeID);
}
// Fix for older content not containing mode fields in the zones
if (contentVersion < (int)EntityVersion::ZoneLightInheritModes && (properties.getType() == EntityTypes::EntityType::Zone)) {
// The legacy version had no keylight mode - this is set to on
properties.setKeyLightMode(COMPONENT_MODE_ENABLED);
// The ambient URL has been moved from "keyLight" to "ambientLight"
if (entityMap.contains("keyLight")) {
QVariantMap keyLightObject = entityMap["keyLight"].toMap();
properties.getAmbientLight().setAmbientURL(keyLightObject["ambientURL"].toString());
}
// Copy the skybox URL if the ambient URL is empty, as this is the legacy behaviour
// Use skybox value only if it is not empty, else set ambientMode to inherit (to use default URL)
properties.setAmbientLightMode(COMPONENT_MODE_ENABLED);
if (properties.getAmbientLight().getAmbientURL() == "") {
if (properties.getSkybox().getURL() != "") {
properties.getAmbientLight().setAmbientURL(properties.getSkybox().getURL());
} else {
properties.setAmbientLightMode(COMPONENT_MODE_INHERIT);
}
}
// The background should be enabled if the mode is skybox
// Note that if the values are default then they are not stored in the JSON file
if (entityMap.contains("backgroundMode") && (entityMap["backgroundMode"].toString() == "skybox")) {
properties.setSkyboxMode(COMPONENT_MODE_ENABLED);
} else {
properties.setSkyboxMode(COMPONENT_MODE_INHERIT);
}
}
// Convert old materials so that they use materialData instead of userData
if (contentVersion < (int)EntityVersion::MaterialData && properties.getType() == EntityTypes::EntityType::Material) {
if (properties.getMaterialURL().startsWith("userData")) {
QString materialURL = properties.getMaterialURL();
properties.setMaterialURL(materialURL.replace("userData", "materialData"));
QJsonObject userData = QJsonDocument::fromJson(properties.getUserData().toUtf8()).object();
QJsonObject materialData;
QJsonValue materialVersion = userData["materialVersion"];
if (!materialVersion.isNull()) {
materialData.insert("materialVersion", materialVersion);
userData.remove("materialVersion");
}
QJsonValue materials = userData["materials"];
if (!materials.isNull()) {
materialData.insert("materials", materials);
userData.remove("materials");
}
properties.setMaterialData(QJsonDocument(materialData).toJson());
properties.setUserData(QJsonDocument(userData).toJson());
}
}
// Convert old cloneable entities so they use cloneableData instead of userData
if (contentVersion < (int)EntityVersion::CloneableData) {
QJsonObject userData = QJsonDocument::fromJson(properties.getUserData().toUtf8()).object();
QJsonObject grabbableKey = userData["grabbableKey"].toObject();
QJsonValue cloneable = grabbableKey["cloneable"];
if (cloneable.isBool() && cloneable.toBool()) {
QJsonValue cloneLifetime = grabbableKey["cloneLifetime"];
QJsonValue cloneLimit = grabbableKey["cloneLimit"];
QJsonValue cloneDynamic = grabbableKey["cloneDynamic"];
QJsonValue cloneAvatarEntity = grabbableKey["cloneAvatarEntity"];
// This is cloneable, we need to convert the properties
properties.setCloneable(true);
properties.setCloneLifetime(cloneLifetime.toInt());
properties.setCloneLimit(cloneLimit.toInt());
properties.setCloneDynamic(cloneDynamic.toBool());
properties.setCloneAvatarEntity(cloneAvatarEntity.toBool());
}
}
// convert old grab-related userData to new grab properties
if (contentVersion < (int)EntityVersion::GrabProperties) {
convertGrabUserDataToProperties(properties);
}
// Zero out the spread values that were fixed in version ParticleEntityFix so they behave the same as before
if (contentVersion < (int)EntityVersion::ParticleEntityFix) {
properties.setRadiusSpread(0.0f);
properties.setAlphaSpread(0.0f);
properties.setColorSpread({0, 0, 0});
}
if (contentVersion < (int)EntityVersion::FixPropertiesFromCleanup) {
if (entityMap.contains("created")) {
quint64 created = QDateTime::fromString(entityMap["created"].toString().trimmed(), Qt::ISODate).toMSecsSinceEpoch() * 1000;
properties.setCreated(created);
}
}
EntityItemPointer entity = addEntity(entityItemID, properties);
if (!entity) {
qCDebug(entities) << "adding Entity failed:" << entityItemID << properties.getType();
success = false;
}
if (entity) {
const QUuid& cloneOriginID = entity->getCloneOriginID();
if (!cloneOriginID.isNull()) {
cloneIDs[cloneOriginID].push_back(entity->getEntityItemID());
}
}
}
for (const auto& entityID : cloneIDs.keys()) {
auto entity = findEntityByID(entityID);
if (entity) {
entity->setCloneIDs(cloneIDs.value(entityID));
}
}
return success;
}
bool EntityTree::writeToJSON(QString& jsonString, const OctreeElementPointer& element) {
QScriptEngine scriptEngine;
RecurseOctreeToJSONOperator theOperator(element, &scriptEngine, jsonString);
withReadLock([&] {
recurseTreeWithOperator(&theOperator);
});
jsonString = theOperator.getJson();
return true;
}
void EntityTree::resetClientEditStats() {
_treeResetTime = usecTimestampNow();
_maxEditDelta = 0;
_totalEditDeltas = 0;
_totalTrackedEdits = 0;
}
void EntityTree::trackIncomingEntityLastEdited(quint64 lastEditedTime, int bytesRead) {
// we don't want to track all edit deltas, just those edits that have happend
// since we connected to this domain. This will filter out all previously created
// content and only track new edits
if (lastEditedTime > _treeResetTime) {
quint64 now = usecTimestampNow();
quint64 sinceEdit = now - lastEditedTime;
_totalEditDeltas += sinceEdit;
_totalEditBytes += bytesRead;
_totalTrackedEdits++;
if (sinceEdit > _maxEditDelta) {
_maxEditDelta = sinceEdit;
}
}
}
int EntityTree::getJointIndex(const QUuid& entityID, const QString& name) const {
EntityTree* nonConstThis = const_cast<EntityTree*>(this);
EntityItemPointer entity = nonConstThis->findEntityByEntityItemID(entityID);
if (!entity) {
return -1;
}
return entity->getJointIndex(name);
}
QStringList EntityTree::getJointNames(const QUuid& entityID) const {
EntityTree* nonConstThis = const_cast<EntityTree*>(this);
EntityItemPointer entity = nonConstThis->findEntityByEntityItemID(entityID);
if (!entity) {
return QStringList();
}
return entity->getJointNames();
}
std::function<QObject*(const QUuid&)> EntityTree::_getEntityObjectOperator = nullptr;
std::function<QSizeF(const QUuid&, const QString&)> EntityTree::_textSizeOperator = nullptr;
std::function<bool()> EntityTree::_areEntityClicksCapturedOperator = nullptr;
QObject* EntityTree::getEntityObject(const QUuid& id) {
if (_getEntityObjectOperator) {
return _getEntityObjectOperator(id);
}
return nullptr;
}
QSizeF EntityTree::textSize(const QUuid& id, const QString& text) {
if (_textSizeOperator) {
return _textSizeOperator(id, text);
}
return QSizeF(0.0f, 0.0f);
}
bool EntityTree::areEntityClicksCaptured() {
if (_areEntityClicksCapturedOperator) {
return _areEntityClicksCapturedOperator();
}
return false;
}
void EntityTree::updateEntityQueryAACubeWorker(SpatiallyNestablePointer object, EntityEditPacketSender* packetSender,
MovingEntitiesOperator& moveOperator, bool force, bool tellServer) {
// if the queryBox has changed, tell the entity-server
EntityItemPointer entity = std::dynamic_pointer_cast<EntityItem>(object);
if (entity) {
bool queryAACubeChanged = false;
if (!entity->hasChildren()) {
// updateQueryAACube will also update all ancestors' AACubes, so we only need to call this for leaf nodes
queryAACubeChanged = entity->updateQueryAACube();
} else {
AACube oldCube = entity->getQueryAACube();
object->forEachChild([&](SpatiallyNestablePointer descendant) {
updateEntityQueryAACubeWorker(descendant, packetSender, moveOperator, force, tellServer);
});
queryAACubeChanged = oldCube != entity->getQueryAACube();
}
if (queryAACubeChanged || force) {
bool success;
AACube newCube = entity->getQueryAACube(success);
if (success) {
moveOperator.addEntityToMoveList(entity, newCube);
}
// send an edit packet to update the entity-server about the queryAABox. We do this for domain-hosted
// entities as well as for avatar-entities; the packet-sender will route the update accordingly
if (tellServer && packetSender && (entity->isDomainEntity() || entity->isAvatarEntity())) {
quint64 now = usecTimestampNow();
EntityItemProperties properties = entity->getProperties();
properties.setQueryAACubeDirty();
properties.setLocationDirty();
properties.setLastEdited(now);
packetSender->queueEditEntityMessage(PacketType::EntityEdit, getThisPointer(), entity->getID(), properties);
entity->setLastEdited(now); // so we ignore the echo from the server
entity->setLastBroadcast(now); // for debug/physics status icons
}
entity->markDirtyFlags(Simulation::DIRTY_POSITION);
entityChanged(entity);
}
}
}
void EntityTree::updateEntityQueryAACube(SpatiallyNestablePointer object, EntityEditPacketSender* packetSender,
bool force, bool tellServer) {
// This is used when something other than a script or physics moves an entity. We need to put it in the
// correct place in our local octree, update its and its children's queryAACubes, and send an edit
// packet to the entity-server.
MovingEntitiesOperator moveOperator;
updateEntityQueryAACubeWorker(object, packetSender, moveOperator, force, tellServer);
if (moveOperator.hasMovingEntities()) {
PerformanceTimer perfTimer("recurseTreeWithOperator");
recurseTreeWithOperator(&moveOperator);
}
}
|
#define __CLUCK2SESAME_PLATFORM_MCLRRESET_ASM
#include "Platform.inc"
#include "TailCalls.inc"
#include "ResetFlags.inc"
radix decimal
extern initialiseAfterReset
MclrReset code
global initialiseAfterMclrReset
initialiseAfterMclrReset:
.safelySetBankFor PCON
movlw (1 << NOT_BOR) | (1 << NOT_POR)
movwf PCON
.setBankFor resetFlags
clrf resetFlags
tcall initialiseAfterReset
end
|
// Boost.Range library
//
// Copyright Thorsten Ottosen 2003-2004. Use, modification and
// distribution is subject to the Boost Software License, Version
// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// For more information, see http://www.boost.org/libs/range/
//
#ifndef BOOST_RANGE_SIZE_TYPE_HPP
#define BOOST_RANGE_SIZE_TYPE_HPP
#if defined(_MSC_VER)
# pragma once
#endif
#include <boost/range/config.hpp>
#include <boost/range/difference_type.hpp>
#include <boost/range/concepts.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/make_unsigned.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <cstddef>
#include <utility>
namespace boost
{
namespace detail
{
//////////////////////////////////////////////////////////////////////////
// default
//////////////////////////////////////////////////////////////////////////
template<typename T>
class has_size_type
{
typedef char no_type;
struct yes_type { char dummy[2]; };
template<typename C>
static yes_type test(BOOST_DEDUCED_TYPENAME C::size_type x);
template<typename C>
static no_type test(...);
public:
static const bool value = sizeof(test<T>(0)) == sizeof(yes_type);
};
template<typename C, typename Enabler=void>
struct range_size
{
typedef BOOST_DEDUCED_TYPENAME make_unsigned<
BOOST_DEDUCED_TYPENAME range_difference<C>::type
>::type type;
};
template<typename C>
struct range_size<
C,
BOOST_DEDUCED_TYPENAME enable_if<has_size_type<C>, void>::type
>
{
typedef BOOST_DEDUCED_TYPENAME C::size_type type;
};
}
template< class T >
struct range_size :
detail::range_size<T>
{
// Very strange things happen on some compilers that have the range concept
// asserts disabled. This preprocessor condition is clearly redundant on a
// working compiler but is vital for at least some compilers such as clang 4.2
// but only on the Mac!
#if BOOST_RANGE_ENABLE_CONCEPT_ASSERT == 1
BOOST_RANGE_CONCEPT_ASSERT((boost::SinglePassRangeConcept<T>));
#endif
};
template< class T >
struct range_size<const T >
: detail::range_size<T>
{
#if BOOST_RANGE_ENABLE_CONCEPT_ASSERT == 1
BOOST_RANGE_CONCEPT_ASSERT((boost::SinglePassRangeConcept<T>));
#endif
};
} // namespace boost
#endif
|
; A169998: a(0)=1, a(1)=1; thereafter a(n) = -a(n-1) - 2*a(n-2).
; 1,1,-3,1,5,-7,-3,17,-11,-23,45,1,-91,89,93,-271,85,457,-627,-287,1541,-967,-2115,4049,181,-8279,7917,8641,-24475,7193,41757,-56143,-27371,139657,-84915,-194399,364229,24569,-753027,703889,802165,-2209943,605613,3814273,-5025499,-2603047
mov $1,2
mov $3,-4
lpb $0,1
sub $0,1
mov $2,$1
add $2,$1
sub $1,$3
sub $1,$2
mov $3,$2
lpe
div $1,2
|
; A053737: Sum of digits of (n written in base 4).
; 0,1,2,3,1,2,3,4,2,3,4,5,3,4,5,6,1,2,3,4,2,3,4,5,3,4,5,6,4,5,6,7,2,3,4,5,3,4,5,6,4,5,6,7,5,6,7,8,3,4,5,6,4,5,6,7,5,6,7,8,6,7,8,9,1,2,3,4,2,3,4,5,3,4,5,6,4,5,6,7,2,3,4,5,3,4,5,6,4,5,6,7,5,6,7,8,3,4,5,6,4,5,6,7,5,6,7,8,6,7,8,9,4,5,6,7,5,6,7,8,6,7,8,9,7,8,9,10,2,3,4,5,3,4,5,6,4,5,6,7,5,6,7,8,3,4,5,6,4,5,6,7,5,6,7,8,6,7,8,9,4,5,6,7,5,6,7,8,6,7,8,9,7,8,9,10,5,6,7,8,6,7,8,9,7,8,9,10,8,9,10,11,3,4,5,6,4,5,6,7,5,6,7,8,6,7,8,9,4,5,6,7,5,6,7,8,6,7,8,9,7,8,9,10,5,6,7,8,6,7,8,9,7,8,9,10,8,9,10,11,6,7,8,9,7,8,9,10,8,9
mov $2,$0
sub $0,1
lpb $0,1
div $2,4
mov $3,3
mul $3,$2
sub $0,$3
lpe
mov $1,$0
add $1,1
|
#include <torch/csrc/jit/frontend/ir_emitter.h>
#include <torch/csrc/jit/jit_log.h>
#include <torch/csrc/jit/passes/inliner.h>
#include <torch/csrc/jit/runtime/operator.h>
#include <torch/csrc/jit/runtime/symbolic_shape_registry.h>
#include <unordered_map>
namespace torch {
namespace jit {
namespace {
std::mutex lock;
const std::string shape_compute_functions =
R"(
#### SHAPE COMPUTE FUNCTIONS ###
def broadcast(a: List[int], b: List[int]):
dimsA = len(a)
dimsB = len(b)
ndim = max(dimsA, dimsB)
expandedSizes : List[int] = []
for i in range(ndim):
offset = ndim - 1 - i
dimA = dimsA - 1 - offset
dimB = dimsB - 1 - offset
sizeA = a[dimA] if (dimA >= 0) else 1
sizeB = b[dimB] if (dimB >= 0) else 1
if sizeA != sizeB and sizeA != 1 and sizeB != 1:
# TODO: only assertion error is bound in C++ compilation right now
raise AssertionError("The size of tensor a {} must match the size of tensor b ("
"{}) at non-singleton dimension {}".format(sizeA, sizeB, i))
expandedSizes.append(sizeB if sizeA == 1 else sizeA)
return expandedSizes
def adaptive_avg_pool2d(self: List[int], out: List[int]):
# TODO: return out directly, list len refiner would need to
# annotate the List Type with len directly in IR
assert len(out) == 2
return [out[0], out[1]]
# TODO: maybe make it customary that extra arguments are unused ?
# TODO: return self directly
def unary_two_unused_inputs(self: List[int], inp0: Any, inp1: Any):
out: List[int] = []
for elem in self:
out.append(elem)
return out
def unary_one_unused_input(self: List[int], inp0: Any):
out: List[int] = []
for elem in self:
out.append(elem)
return out
def unary(self: List[int]):
out: List[int] = []
for elem in self:
out.append(elem)
return out
def view(self: List[int], sizes: List[int]):
# TODO: add assertions to check whether requested dims are valid
out: List[int] = []
for elem in sizes:
if elem == -1:
# TODO: support -1 in view dimensions
raise AssertionError("Shape function doesn't support -1 view dims yet")
out.append(elem)
return out
def mean_dim(self: List[int], dims: List[int], keep_dim: bool, dt : Any):
out: List[int] = []
for idx in range(len(self)):
is_mean_dim : bool = False
for reduce_dim in dims:
if idx == maybe_wrap_dim(reduce_dim, len(self)):
is_mean_dim = True
if is_mean_dim:
if keep_dim:
out.append(1)
else:
out.append(self[idx])
return out
def broadcast_one_unused_input(self: List[int], other: List[int], unused: Any):
return broadcast(self, other)
def mm(self: List[int] , mat2: List[int]):
assert len(self) == 2, "self must be a matrix"
assert len(mat2) == 2, "mat2 must be a matrix"
assert self[1] == mat2[0]
return [self[0], mat2[1]]
def dot(self: List[int], tensor: List[int]):
assert len(self) == 1 and len(tensor) == 1
assert self[0] == tensor[0]
out: List[int] = []
return out
def mv(self: List[int], vec: List[int]):
assert len(self) == 2 and len(vec) == 1
assert self[1] == vec[0]
# TODO: return self
return [self[0]]
# TODO: optional dim, then expose as a registered shape function
def unsqueeze(li: List[int], dim: int):
out: List[int] = []
for i in range(len(li)):
if i == dim:
out.append(1)
out.append(li[i])
return out
# TODO: optional dim, then expose as a registered shape function
def squeeze(li: List[int], dim: int):
out: List[int] = []
for i in range(len(li)):
if i == dim:
if li[i] != 1:
out.append(li[i])
else:
out.append(li[i])
return out
def matmul(tensor1: List[int] , tensor2: List[int]):
dim_tensor1 = len(tensor1)
dim_tensor2 = len(tensor2)
if dim_tensor1 == 1 and dim_tensor2 == 1:
return dot(tensor1, tensor2)
elif dim_tensor1 == 2 and dim_tensor2 == 1:
return mv(tensor1, tensor2)
elif dim_tensor1 == 1 and dim_tensor2 == 2:
return squeeze(mm(unsqueeze(tensor1, 0), tensor2), 0)
elif dim_tensor1 == 2 and dim_tensor2 == 2:
return mm(tensor1, tensor2)
elif dim_tensor1 >= 1 and dim_tensor2 >=1:
# We are multiplying b1 x n x m1 by x2 x m2 x p (where b1 can be a list);
# we track m1 vs m2 separately even though they must match for nicer error messages
n = tensor1[-2] if dim_tensor1 > 1 else 1
m1 = tensor1[-1]
batch_tensor1 : List[int] = []
# TODO: handling of slice
for i in range(dim_tensor1 - 2):
batch_tensor1.append(tensor1[i])
m2 = tensor2[-1] if dim_tensor2 > 1 else 1
p = tensor2[-1]
batch_tensor2 : List[int] = []
# TODO: handling of slice
for i in range(dim_tensor2 - 2):
batch_tensor2.append(tensor2[i])
# expand the batch portion (i.e. cut off matrix dimensions and expand rest)
expand_batch_portion = broadcast(batch_tensor1, batch_tensor2)
# todo: copy ?
output_shape = expand_batch_portion
if dim_tensor1 > 1:
output_shape.append(n)
if dim_tensor2 > 1:
output_shape.append(p)
return output_shape
else:
assert False, "both arguments to matmul need to be at least 1D"
def t(self: List[int]):
assert len(self) <= 2
self_len = len(self)
if self_len == 0:
out: List[int] = []
return out
elif self_len == 1:
return [self[0]]
else:
return [self[1], self[0]]
def linear(input: List[int], weight: List[int], bias: Optional[List[int]]):
out = matmul(input, t(weight))
if bias is not None:
assert broadcast(bias, out) == out
return out
def addmm(self: List[int], mat1: List[int], mat2: List[int], beta: Any, alpha: Any):
return broadcast(self, mm(mat1, mat2))
def check_non_negative(array: List[int]) -> bool:
# TODO: look into rewriting with early return and getting loop unrolling to fire
non_negative = False
for val in array:
if val < 0:
non_negative = True
return non_negative
def check_shape_forward(input: List[int], weight_sizes: List[int], bias: Optional[List[int]], stride: List[int], padding: List[int], dilation: List[int], groups: int):
k = len(input)
weight_dim = len(weight_sizes)
# TODO: assertions could be expanded with the error messages
assert not check_non_negative(padding)
assert not check_non_negative(stride)
assert weight_dim == k
assert weight_sizes[0] >= groups
assert (weight_sizes[0] % groups) == 0
# only handling not transposed
assert input[1] == weight_sizes[1] * groups
assert bias is None or (len(bias) == 1 and bias[0] == weight_sizes[0])
for i in range(2, k):
assert (input[i] + 2 * padding[i - 2]) >= (dilation[i - 2] * (weight_sizes[i] - 1) + 1)
# this is not handling transposed convolution yet
def conv_output_size(input_size: List[int], weight_size: List[int], bias: Optional[List[int]], stride: List[int], padding: List[int], dilation: List[int], groups: int):
check_shape_forward(input_size, weight_size, bias, stride, padding, dilation, groups)
has_dilation = len(dilation) > 0
dim = len(input_size)
output_size: List[int] = []
input_batch_size_dim = 0
weight_output_channels_dim = 0
output_size.append(input_size[input_batch_size_dim])
output_size.append(weight_size[weight_output_channels_dim])
for d in range(2, dim):
dilation_ = dilation[d - 2] if has_dilation else 1
kernel = dilation_ * (weight_size[d] - 1) + 1
output_size.append((input_size[d] + (2 * padding[d - 2]) - kernel) // stride[d - 2] + 1)
return output_size
def conv1d(input: List[int], weight: List[int], bias: Optional[List[int]], stride: List[int], padding: List[int], dilation: List[int], groups: int):
assert len(weight) == 3
assert len(input) == 3
return conv_output_size(input, weight, bias, stride, padding, dilation, groups)
def conv2d(input: List[int], weight: List[int], bias: Optional[List[int]], stride: List[int], padding: List[int], dilation: List[int], groups: int):
assert len(weight) == 4
assert len(input) == 4
return conv_output_size(input, weight, bias, stride, padding, dilation, groups)
def conv3d(input: List[int], weight: List[int], bias: Optional[List[int]], stride: List[int], padding: List[int], dilation: List[int], groups: int):
assert len(weight) == 5
assert len(input) == 5
return conv_output_size(input, weight, bias, stride, padding, dilation, groups)
def maybe_wrap_dim(dim: int, dim_post_expr: int, wrap_scalar: bool = True):
if dim_post_expr <= 0:
assert wrap_scalar
dim_post_expr = 1
min = -dim_post_expr
max = dim_post_expr - 1
assert not (dim < min or dim > max)
if dim < 0:
dim += dim_post_expr
return dim
def multiply_integers(li: List[int]):
out = 1
for elem in li:
out = out * elem
return out
def flatten(input: List[int], start_dim: int, end_dim: int):
start_dim = maybe_wrap_dim(start_dim, len(input))
end_dim = maybe_wrap_dim(end_dim, len(input))
assert start_dim <= end_dim
if len(input) == 0:
return [1]
if (start_dim == end_dim):
# TODO: return self
out: List[int] = []
for elem in input:
out.append(elem)
return out
slice_numel = multiply_integers(input[start_dim:end_dim - start_dim + 1])
shape: List[int] = []
for i in range(start_dim):
shape.append(input[i])
shape.append(slice_numel)
for i in range(end_dim + 1, len(input)):
shape.append(input[i])
return shape
)";
// mapping function schema to shape compute graphs allows multiple functions to
// share the same shape compute graph, which is memory efficient and also will
// help speed up shape analysis by caching the result of running consecutive ops
// for a particular set of inputs with the same graph, e.g. running a series
// of pointwise ops
// we need a map from schema to shape compute graph, because the aten schema
// is not recoverable from the shape compute graph, since the shape compute
// graph replaces Tensor inputs with List[int] and there are operators like Conv
// which natively have List[int] inputs
// TODO: consider storing shape compute graph directly on operator,
// and merge into native_functions.yaml
// wrapped in function so that operators get registered before map is
// initialized
static const OperatorMap<std::string>& get_schema_to_function_graph() {
// clang-format off
static const OperatorMap<std::string> schema_to_function_graph{
{"aten::mul.Tensor(Tensor self, Tensor other) -> Tensor", "broadcast"},
{"aten::mul.Scalar(Tensor self, Scalar other) -> Tensor", "unary_one_unused_input"},
{"aten::div.Tensor(Tensor self, Tensor other) -> Tensor", "broadcast"},
{"aten::div.Scalar(Tensor self, Scalar other) -> Tensor", "unary_one_unused_input"},
{"aten::gt.Tensor(Tensor self, Tensor other) -> Tensor", "broadcast"},
{"aten::add.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor", "broadcast_one_unused_input"},
{"aten::add.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor", "unary_two_unused_inputs"},
{"aten::hardtanh(Tensor self, Scalar min_val=-1, Scalar max_val=1) -> Tensor", "unary_two_unused_inputs"},
{"aten::adaptive_avg_pool2d(Tensor self, int[2] output_size) -> Tensor", "adaptive_avg_pool2d"},
{"aten::mm(Tensor self, Tensor mat2) -> Tensor", "mm"},
{"aten::dot(Tensor self, Tensor tensor) -> Tensor", "dot"},
{"aten::mv(Tensor self, Tensor vec) -> Tensor", "mv"},
{"aten::matmul(Tensor self, Tensor other) -> Tensor", "matmul"},
{"aten::linear(Tensor input, Tensor weight, Tensor? bias=None) -> Tensor", "linear"},
{"aten::t(Tensor(a) self) -> Tensor(a)", "t"},
{"aten::conv1d(Tensor input, Tensor weight, Tensor? bias=None, int[1] stride=1, int[1] padding=0, int[1] dilation=1, int groups=1) -> Tensor", "conv1d"},
{"aten::conv2d(Tensor input, Tensor weight, Tensor? bias=None, int[2] stride=1, int[2] padding=0, int[2] dilation=1, int groups=1) -> Tensor", "conv2d"},
{"aten::conv3d(Tensor input, Tensor weight, Tensor? bias=None, int[3] stride=1, int[3] padding=0, int[3] dilation=1, int groups=1) -> Tensor", "conv3d"},
{"aten::flatten.using_ints(Tensor(a) self, int start_dim=0, int end_dim=-1) -> Tensor(a)", "flatten"},
{"aten::relu(Tensor self) -> Tensor", "unary"},
{"aten::view(Tensor(a) self, int[] size) -> Tensor(a)", "view"},
{"aten::expand_as(Tensor(a) self, Tensor other) -> Tensor(a)", "view"},
{"aten::mean.dim(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor", "mean_dim"},
{"aten::addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor", "addmm"},
};
// clang-format on
return schema_to_function_graph;
}
std::unordered_map<const FunctionSchema*, std::shared_ptr<Graph>>
cached_schema_to_graph;
// CompilationUnit that holds all these Functions and keeps them alive.
CompilationUnit compilation_unit;
void loadModule(const CompilationUnit& module) {
std::unordered_map<std::string, std::shared_ptr<Graph>> reused_functions;
for (const auto& pair :
get_schema_to_function_graph().getAllKeysAndValues()) {
const FunctionSchema* schema_string = &pair.first->schema();
const std::string& shape_compute_function_name = pair.second;
if (reused_functions.count(shape_compute_function_name)) {
cached_schema_to_graph[schema_string] =
reused_functions[shape_compute_function_name];
continue;
}
Function& shape_compute_function =
module.get_function(shape_compute_function_name);
std::shared_ptr<Graph> graph = shape_compute_function.graph();
Inline(*graph);
cached_schema_to_graph[schema_string] = graph;
reused_functions[shape_compute_function_name] = graph;
}
}
void loadFunctions() {
compilation_unit.define(
c10::nullopt, shape_compute_functions, nativeResolver(), nullptr);
loadModule(compilation_unit);
}
} // anonymous namespace
c10::optional<std::shared_ptr<Graph>> shapeComputeGraphForSchema(
const FunctionSchema& schema) {
std::lock_guard<std::mutex> guard(lock);
if (cached_schema_to_graph.size() == 0) {
loadFunctions();
}
GRAPH_DEBUG("Trying to find schema: ", schema);
auto cache_it = cached_schema_to_graph.find(&schema);
if (cache_it != cached_schema_to_graph.end()) {
return cache_it->second;
}
GRAPH_DEBUG("Could not find schema: ", schema);
return c10::nullopt;
}
} // namespace jit
} // namespace torch
|
SECTION code_fp_am9511
PUBLIC acos_fastcall
EXTERN asm_am9511_acos_fastcall
defc acos_fastcall = asm_am9511_acos_fastcall
; SDCC bridge for Classic
IF __CLASSIC
PUBLIC _acos_fastcall
defc _acos_fastcall = asm_am9511_acos_fastcall
ENDIF
|
#include "Renderer.h"
Renderer::Renderer() {
}
Renderer::~Renderer() {
for (auto mit = mSpriteCache.begin(); mit != mSpriteCache.end(); mit++) {
delete mit->second;
}
mSpriteCache.clear();
}
void Renderer::RenderSprite(GLTexture* texture, Camera& camera, float x, float y, float w, float h, float a) {
Sprite2D* s = CacheSprite(texture);
s->SetAlpha(a);
s->Draw(camera, x, y, w, h);
}
Sprite2D* Renderer::CacheSprite(GLTexture* texture) {
auto mit = mSpriteCache.find(texture);
if (mit == mSpriteCache.end()) {
Sprite2D* spr = new Sprite2D();
spr->Init(texture);
mSpriteCache[texture] = spr;
return spr;
}
else {
return mit->second;
}
} |
; A166781: Number of nX3 1..2 arrays containing at least one of each value, all equal values connected, and rows considered as a single number in nondecreasing order.
; 4,17,44,91,164,269,412,599,836,1129,1484,1907,2404,2981,3644,4399,5252,6209,7276,8459,9764,11197,12764,14471,16324,18329,20492,22819,25316,27989,30844,33887,37124,40561,44204,48059,52132,56429,60956,65719,70724
mov $1,$0
add $0,2
mul $1,$0
add $1,4
mul $0,$1
sub $0,4
|
// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/fundin-config.h"
#endif
#include "optionsdialog.h"
#include "ui_optionsdialog.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "obfuscation.h"
#include "optionsmodel.h"
#include "main.h" // for MAX_SCRIPTCHECK_THREADS
#include "netbase.h"
#include "txdb.h" // for -dbcache defaults
#ifdef ENABLE_WALLET
#include "wallet.h" // for CWallet::minTxFee
#endif
#include <boost/thread.hpp>
#include <QDataWidgetMapper>
#include <QDir>
#include <QIntValidator>
#include <QLocale>
#include <QMessageBox>
#include <QTimer>
OptionsDialog::OptionsDialog(QWidget* parent, bool enableWallet) : QDialog(parent),
ui(new Ui::OptionsDialog),
model(0),
mapper(0),
fProxyIpValid(true)
{
ui->setupUi(this);
GUIUtil::restoreWindowGeometry("nOptionsDialogWindow", this->size(), this);
/* Main elements init */
ui->databaseCache->setMinimum(nMinDbCache);
ui->databaseCache->setMaximum(nMaxDbCache);
ui->threadsScriptVerif->setMinimum(-(int)boost::thread::hardware_concurrency());
ui->threadsScriptVerif->setMaximum(MAX_SCRIPTCHECK_THREADS);
/* Network elements init */
#ifndef USE_UPNP
ui->mapPortUpnp->setEnabled(false);
#endif
ui->proxyIp->setEnabled(false);
ui->proxyPort->setEnabled(false);
ui->proxyPort->setValidator(new QIntValidator(1, 65535, this));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));
ui->proxyIp->installEventFilter(this);
ui->proxyPort->installEventFilter(this);
/* Window elements init */
#ifdef Q_OS_MAC
/* remove Window tab on Mac */
ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow));
#endif
/* remove Wallet tab in case of -disablewallet */
if (!enableWallet) {
ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWallet));
}
/* Display elements init */
/* Number of displayed decimal digits selector */
QString digits;
for (int index = 2; index <= 8; index++) {
digits.setNum(index);
ui->digits->addItem(digits, digits);
}
/* Theme selector static themes */
ui->theme->addItem(QString("Default"), QVariant("default"));
/* Preferred Zerocoin Denominations */
ui->preferredDenom->addItem(QString(tr("Any")), QVariant("0"));
ui->preferredDenom->addItem(QString("1"), QVariant("1"));
ui->preferredDenom->addItem(QString("5"), QVariant("5"));
ui->preferredDenom->addItem(QString("10"), QVariant("10"));
ui->preferredDenom->addItem(QString("50"), QVariant("50"));
ui->preferredDenom->addItem(QString("100"), QVariant("100"));
ui->preferredDenom->addItem(QString("500"), QVariant("500"));
ui->preferredDenom->addItem(QString("1000"), QVariant("1000"));
ui->preferredDenom->addItem(QString("5000"), QVariant("5000"));
/* Theme selector external themes */
boost::filesystem::path pathAddr = GetDataDir() / "themes";
QDir dir(pathAddr.string().c_str());
dir.setFilter(QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);
QFileInfoList list = dir.entryInfoList();
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
ui->theme->addItem(fileInfo.fileName(), QVariant(fileInfo.fileName()));
}
/* Language selector */
QDir translations(":translations");
ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
foreach (const QString& langStr, translations.entryList()) {
QLocale locale(langStr);
/** check if the locale name consists of 2 parts (language_country) */
if (langStr.contains("_")) {
#if QT_VERSION >= 0x040800
/** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
} else {
#if QT_VERSION >= 0x040800
/** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language (locale name)", e.g. "German (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
}
#if QT_VERSION >= 0x040700
ui->thirdPartyTxUrls->setPlaceholderText("https://example.com/tx/%s");
#endif
ui->unit->setModel(new BitcoinUnits(this));
/* Widget-to-option mapper */
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
mapper->setOrientation(Qt::Vertical);
/* setup/change UI elements when proxy IP is invalid/valid */
connect(this, SIGNAL(proxyIpChecks(QValidatedLineEdit*, QLineEdit*)), this, SLOT(doProxyIpChecks(QValidatedLineEdit*, QLineEdit*)));
}
OptionsDialog::~OptionsDialog()
{
GUIUtil::saveWindowGeometry("nOptionsDialogWindow", this);
delete ui;
}
void OptionsDialog::setModel(OptionsModel* model)
{
this->model = model;
if (model) {
/* check if client restart is needed and show persistent message */
if (model->isRestartRequired())
showRestartWarning(true);
QString strLabel = model->getOverriddenByCommandLine();
if (strLabel.isEmpty())
strLabel = tr("none");
ui->overriddenByCommandLineLabel->setText(strLabel);
mapper->setModel(model);
setMapper();
mapper->toFirst();
}
/* warn when one of the following settings changes by user action (placed here so init via mapper doesn't trigger them) */
/* Main */
connect(ui->databaseCache, SIGNAL(valueChanged(int)), this, SLOT(showRestartWarning()));
connect(ui->threadsScriptVerif, SIGNAL(valueChanged(int)), this, SLOT(showRestartWarning()));
/* Wallet */
connect(ui->spendZeroConfChange, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));
/* Network */
connect(ui->allowIncoming, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));
connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));
/* Display */
connect(ui->digits, SIGNAL(valueChanged()), this, SLOT(showRestartWarning()));
connect(ui->theme, SIGNAL(valueChanged()), this, SLOT(showRestartWarning()));
connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning()));
connect(ui->thirdPartyTxUrls, SIGNAL(textChanged(const QString&)), this, SLOT(showRestartWarning()));
connect(ui->showMasternodesTab, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));
}
void OptionsDialog::setMapper()
{
/* Main */
mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup);
mapper->addMapping(ui->threadsScriptVerif, OptionsModel::ThreadsScriptVerif);
mapper->addMapping(ui->databaseCache, OptionsModel::DatabaseCache);
// Zeromint Enabled
mapper->addMapping(ui->checkBoxZeromintEnable, OptionsModel::ZeromintEnable);
// Zerocoin mint percentage
mapper->addMapping(ui->zeromintPercentage, OptionsModel::ZeromintPercentage);
// Zerocoin preferred denomination
mapper->addMapping(ui->preferredDenom, OptionsModel::ZeromintPrefDenom);
/* Wallet */
mapper->addMapping(ui->spendZeroConfChange, OptionsModel::SpendZeroConfChange);
mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures);
mapper->addMapping(ui->spinBoxStakeSplitThreshold, OptionsModel::StakeSplitThreshold);
/* Network */
mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP);
mapper->addMapping(ui->allowIncoming, OptionsModel::Listen);
mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse);
mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP);
mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort);
/* Window */
#ifndef Q_OS_MAC
mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray);
mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose);
#endif
/* Display */
mapper->addMapping(ui->digits, OptionsModel::Digits);
mapper->addMapping(ui->theme, OptionsModel::Theme);
mapper->addMapping(ui->theme, OptionsModel::Theme);
mapper->addMapping(ui->lang, OptionsModel::Language);
mapper->addMapping(ui->unit, OptionsModel::DisplayUnit);
mapper->addMapping(ui->thirdPartyTxUrls, OptionsModel::ThirdPartyTxUrls);
mapper->addMapping(ui->checkBoxHideZeroBalances, OptionsModel::HideZeroBalances);
/* Masternode Tab */
mapper->addMapping(ui->showMasternodesTab, OptionsModel::ShowMasternodesTab);
}
void OptionsDialog::enableOkButton()
{
/* prevent enabling of the OK button when data modified, if there is an invalid proxy address present */
if (fProxyIpValid)
setOkButtonState(true);
}
void OptionsDialog::disableOkButton()
{
setOkButtonState(false);
}
void OptionsDialog::setOkButtonState(bool fState)
{
ui->okButton->setEnabled(fState);
}
void OptionsDialog::on_resetButton_clicked()
{
if (model) {
// confirmation dialog
QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm options reset"),
tr("Client restart required to activate changes.") + "<br><br>" + tr("Client will be shutdown, do you want to proceed?"),
QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
if (btnRetVal == QMessageBox::Cancel)
return;
/* reset all options and close GUI */
model->Reset();
QApplication::quit();
}
}
void OptionsDialog::on_okButton_clicked()
{
mapper->submit();
obfuScationPool.cachedNumBlocks = std::numeric_limits<int>::max();
pwalletMain->MarkDirty();
accept();
}
void OptionsDialog::on_cancelButton_clicked()
{
reject();
}
void OptionsDialog::showRestartWarning(bool fPersistent)
{
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
if (fPersistent) {
ui->statusLabel->setText(tr("Client restart required to activate changes."));
} else {
ui->statusLabel->setText(tr("This change would require a client restart."));
// clear non-persistent status label after 10 seconds
// Todo: should perhaps be a class attribute, if we extend the use of statusLabel
QTimer::singleShot(10000, this, SLOT(clearStatusLabel()));
}
}
void OptionsDialog::clearStatusLabel()
{
ui->statusLabel->clear();
}
void OptionsDialog::doProxyIpChecks(QValidatedLineEdit* pUiProxyIp, QLineEdit* pUiProxyPort)
{
const std::string strAddrProxy = pUiProxyIp->text().toStdString();
CService addrProxy;
// Check for a valid IPv4 / IPv6 address
if (!(fProxyIpValid = LookupNumeric(strAddrProxy.c_str(), addrProxy))) {
disableOkButton();
pUiProxyIp->setValid(false);
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
ui->statusLabel->setText(tr("The supplied proxy address is invalid."));
return;
}
// Check proxy port
if (!pUiProxyPort->hasAcceptableInput()){
disableOkButton();
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
ui->statusLabel->setText(tr("The supplied proxy port is invalid."));
return;
}
proxyType checkProxy = proxyType(addrProxy);
if (!checkProxy.IsValid()) {
disableOkButton();
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
ui->statusLabel->setText(tr("The supplied proxy settings are invalid."));
return;
}
enableOkButton();
ui->statusLabel->clear();
}
bool OptionsDialog::eventFilter(QObject* object, QEvent* event)
{
if (event->type() == QEvent::FocusOut) {
if (object == ui->proxyIp || object == ui->proxyPort) {
emit proxyIpChecks(ui->proxyIp, ui->proxyPort);
}
}
return QDialog::eventFilter(object, event);
}
|
/*
* DGSWriter.hpp
*
* Created on: 14.01.2014
* Author: cls
*/
#ifndef NETWORKIT_DYNAMICS_DGS_WRITER_HPP_
#define NETWORKIT_DYNAMICS_DGS_WRITER_HPP_
#include <string>
#include <vector>
#include <networkit/dynamics/GraphEvent.hpp>
namespace NetworKit {
/**
* @ingroup dynamics
*/
class DGSWriter final {
public:
DGSWriter() = default;
void write(std::vector<GraphEvent>& stream, const std::string& path);
};
} /* namespace NetworKit */
#endif // NETWORKIT_DYNAMICS_DGS_WRITER_HPP_
|
; $Id: bs3-cpu-instr-2-asm.asm 69222 2017-10-24 15:10:29Z vboxsync $
;; @file
; BS3Kit - bs3-cpu-instr-2
;
;
; Copyright (C) 2007-2017 Oracle Corporation
;
; This file is part of VirtualBox Open Source Edition (OSE), as
; available from http://www.virtualbox.org. This file is free software;
; you can redistribute it and/or modify it under the terms of the GNU
; General Public License (GPL) as published by the Free Software
; Foundation, in version 2 as it comes in the "COPYING" file of the
; VirtualBox OSE distribution. VirtualBox OSE is distributed in the
; hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
;
; The contents of this file may alternatively be used under the terms
; of the Common Development and Distribution License Version 1.0
; (CDDL) only, as it comes in the "COPYING.CDDL" file of the
; VirtualBox OSE distribution, in which case the provisions of the
; CDDL are applicable instead of those of the GPL.
;
; You may elect to license modified versions of this file under the
; terms and conditions of either the GPL or the CDDL or both.
;
;*********************************************************************************************************************************
;* Header Files *
;*********************************************************************************************************************************
%include "bs3kit.mac"
;*********************************************************************************************************************************
;* Global Variables *
;*********************************************************************************************************************************
;BS3_BEGIN_DATA16
;BS3_GLOBAL_DATA g_bs3CpuBasic2_ud2_FlatAddr, 4
; dd _bs3CpuBasic2_ud2 wrt FLAT
;
; CPU mode agnostic test code snippets.
;
BS3_BEGIN_TEXT16
BS3_PROC_BEGIN _bs3CpuInstr2_imul_bl_ud2
imul bl
.again:
ud2
jmp .again
BS3_PROC_END _bs3CpuInstr2_imul_bl_ud2
;
; Instantiate code templates.
;
BS3_INSTANTIATE_COMMON_TEMPLATE "bs3-cpu-instr-2-template.mac"
BS3_INSTANTIATE_TEMPLATE_WITH_WEIRD_ONES "bs3-cpu-instr-2-template.mac"
|
; A112232: Repeat each composite number in the sequence of natural numbers.
; 1,2,3,4,4,5,6,6,7,8,8,9,9,10,10,11,12,12,13,14,14,15,15,16,16,17,18,18,19,20,20,21,21,22,22,23,24,24,25,25,26,26,27,27,28,28,29,30,30,31,32,32,33,33,34,34,35,35,36,36,37,38,38,39,39,40,40,41,42,42,43,44,44,45
mov $2,$0
lpb $0
seq $0,230980 ; Number of primes <= n, starting at n=0.
mov $3,$4
cmp $3,0
add $4,$3
add $4,$2
add $0,$4
div $0,2
mod $4,$4
lpe
add $0,1
|
;
; Kaypro II pseudo graphics routines
;
; Stefano Bodrato 2018
;
;
; $Id: plot_end_83.asm $
;
SECTION code_graphics
PUBLIC plot_end
PUBLIC plot_decode
EXTERN __gfx_coords
.plot_decode
ld (__gfx_coords),hl
ld c,a
srl a
ld b,a ;y/2
ld a,h
ld hl,$3000 - 128
ld de,128
inc b
yloop: add hl,de
djnz yloop
ld e,a
add hl,de
ld a,(hl)
and a ; ' = top
ld a,1
jr z,ydone
ld a,(hl)
cp ',' ; bottom
ld a,2
jr z,ydone
ld a,(hl)
cp '|' ; top+bottom
ld a,3
jr z,ydone
xor a
.ydone
rr c
ret
.plot_end
push hl
ld hl,chars
add l
ld l,a
jr nc,nocy
inc h
.nocy
ld a,(hl)
pop hl
ld (hl),a
pop bc
ret
chars: defb ' ',0,',','|'
|
; A127216: a(n) = 2^n*tetranacci(n) or (2^n)*A001648(n).
; Submitted by Christian Krause
; 2,12,56,240,832,3264,12672,48896,187904,724992,2795520,10776576,41541632,160153600,617414656,2380201984,9175957504,35374497792,136373075968,525735034880,2026773676032,7813464064000,30121872326656,116123550875648,447670682386432,1725825971912704,6653273037602816,25649192235958272,98880815315812352,381197799426883584,1469564766606327808,5665354329222021120,21840643165337419776,84198386571243683840,324595216703314460672,1251354794281855352832,4824127838592316735488,18597610773078469509120
mov $2,$0
seq $0,1648 ; Tetranacci numbers A073817 without the leading term 4.
lpb $2
mul $0,2
sub $2,1
lpe
mul $0,2
|
<%
import collections
import pwnlib.abi
import pwnlib.constants
import pwnlib.shellcraft
import six
%>
<%docstring>sigaltstack(ss, oss) -> str
Invokes the syscall sigaltstack.
See 'man 2 sigaltstack' for more information.
Arguments:
ss(sigaltstack*): ss
oss(sigaltstack*): oss
Returns:
int
</%docstring>
<%page args="ss=0, oss=0"/>
<%
abi = pwnlib.abi.ABI.syscall()
stack = abi.stack
regs = abi.register_arguments[1:]
allregs = pwnlib.shellcraft.registers.current()
can_pushstr = []
can_pushstr_array = []
argument_names = ['ss', 'oss']
argument_values = [ss, oss]
# Load all of the arguments into their destination registers / stack slots.
register_arguments = dict()
stack_arguments = collections.OrderedDict()
string_arguments = dict()
dict_arguments = dict()
array_arguments = dict()
syscall_repr = []
for name, arg in zip(argument_names, argument_values):
if arg is not None:
syscall_repr.append('%s=%s' % (name, pwnlib.shellcraft.pretty(arg, False)))
# If the argument itself (input) is a register...
if arg in allregs:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[index] = arg
# The argument is not a register. It is a string value, and we
# are expecting a string value
elif name in can_pushstr and isinstance(arg, (six.binary_type, six.text_type)):
if isinstance(arg, six.text_type):
arg = arg.encode('utf-8')
string_arguments[name] = arg
# The argument is not a register. It is a dictionary, and we are
# expecting K:V paris.
elif name in can_pushstr_array and isinstance(arg, dict):
array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()]
# The arguent is not a register. It is a list, and we are expecting
# a list of arguments.
elif name in can_pushstr_array and isinstance(arg, (list, tuple)):
array_arguments[name] = arg
# The argument is not a register, string, dict, or list.
# It could be a constant string ('O_RDONLY') for an integer argument,
# an actual integer value, or a constant.
else:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[target] = arg
# Some syscalls have different names on various architectures.
# Determine which syscall number to use for the current architecture.
for syscall in ['SYS_sigaltstack']:
if hasattr(pwnlib.constants, syscall):
break
else:
raise Exception("Could not locate any syscalls: %r" % syscalls)
%>
/* sigaltstack(${', '.join(syscall_repr)}) */
%for name, arg in string_arguments.items():
${pwnlib.shellcraft.pushstr(arg, append_null=(b'\x00' not in arg))}
${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)}
%endfor
%for name, arg in array_arguments.items():
${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)}
%endfor
%for name, arg in stack_arguments.items():
${pwnlib.shellcraft.push(arg)}
%endfor
${pwnlib.shellcraft.setregs(register_arguments)}
${pwnlib.shellcraft.syscall(syscall)}
|
/***
*
* Copyright (c) 1996-2001, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
/*
===== weapons.cpp ========================================================
functions governing the selection/use of weapons for players
*/
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "CBasePlayer.h"
#include "entities/NPCs/Monsters.h"
#include "Weapons.h"
#include "nodes/Nodes.h"
#include "entities/CSoundEnt.h"
#include "Decals.h"
#include "gamerules/GameRules.h"
DLL_GLOBAL short g_sModelIndexLaser;// holds the index for the laser beam
DLL_GLOBAL const char *g_pModelNameLaser = "sprites/laserbeam.spr";
DLL_GLOBAL short g_sModelIndexLaserDot;// holds the index for the laser beam dot
DLL_GLOBAL short g_sModelIndexFireball;// holds the index for the fireball
DLL_GLOBAL short g_sModelIndexSmoke;// holds the index for the smoke cloud
DLL_GLOBAL short g_sModelIndexWExplosion;// holds the index for the underwater explosion
DLL_GLOBAL short g_sModelIndexBubbles;// holds the index for the bubbles model
DLL_GLOBAL short g_sModelIndexBloodDrop;// holds the sprite index for the initial blood
DLL_GLOBAL short g_sModelIndexBloodSpray;// holds the sprite index for splattered blood
DLL_GLOBAL short g_sModelIndexNullModel; //null model index
DLL_GLOBAL short g_sModelIndexErrorModel;//error model index
DLL_GLOBAL short g_sModelIndexNullSprite;//null sprite index
DLL_GLOBAL short g_sModelIndexErrorSprite;//error sprite index
DLL_GLOBAL short g_sSoundIndexNullSound;//null sound index
DLL_GLOBAL unsigned short g_usEventIndexNullEvent;//null event index
CMultiDamage g_MultiDamage;
/*
================
SpawnBlood
================
*/
void SpawnBlood(Vector vecSpot, int bloodColor, float flDamage)
{
UTIL_BloodDrips( vecSpot, g_vecAttackDir, bloodColor, (int)flDamage );
}
int DamageDecal( CBaseEntity *pEntity, int bitsDamageType )
{
if ( !pEntity )
return (DECAL_GUNSHOT1 + RANDOM_LONG(0,4));
return pEntity->DamageDecal( bitsDamageType );
}
void DecalGunshot( TraceResult *pTrace, int iBulletType )
{
if( !pTrace->pHit )
return;
CBaseEntity* pHit = CBaseEntity::Instance( pTrace->pHit );
// Is the entity valid
if ( !UTIL_IsValidEntity( pHit ) )
return;
if ( pHit->GetSolidType() == SOLID_BSP || pHit->GetMoveType() == MOVETYPE_PUSHSTEP )
{
// Decal the wall with a gunshot
switch( iBulletType )
{
case BULLET_PLAYER_9MM:
case BULLET_MONSTER_9MM:
case BULLET_PLAYER_MP5:
case BULLET_MONSTER_MP5:
case BULLET_PLAYER_BUCKSHOT:
case BULLET_PLAYER_357:
#if USE_OPFOR
case BULLET_PLAYER_556:
case BULLET_PLAYER_762:
case BULLET_PLAYER_DEAGLE:
#endif
default:
// smoke and decal
UTIL_GunshotDecalTrace( pTrace, DamageDecal( pHit, DMG_BULLET ) );
break;
case BULLET_MONSTER_12MM:
// smoke and decal
UTIL_GunshotDecalTrace( pTrace, DamageDecal( pHit, DMG_BULLET ) );
break;
case BULLET_PLAYER_CROWBAR:
// wall decal
UTIL_DecalTrace( pTrace, DamageDecal( pHit, DMG_CLUB ) );
break;
}
}
}
void EjectBrass( const Vector& vecOrigin, const Vector& vecVelocity, float rotation, int model, TE_Bounce soundtype )
{
// FIX: when the player shoots, their gun isn't in the same position as it is on the model other players see.
MESSAGE_BEGIN( MSG_PVS, SVC_TEMPENTITY, vecOrigin );
WRITE_BYTE( TE_MODEL );
WRITE_COORD( vecOrigin.x );
WRITE_COORD( vecOrigin.y );
WRITE_COORD( vecOrigin.z );
WRITE_COORD( vecVelocity.x );
WRITE_COORD( vecVelocity.y );
WRITE_COORD( vecVelocity.z );
WRITE_ANGLE( rotation );
WRITE_SHORT( model );
WRITE_BYTE ( soundtype );
WRITE_BYTE ( 25 );// 2.5 seconds
MESSAGE_END();
}
#if 0
// UNDONE: This is no longer used?
void ExplodeModel( const Vector &vecOrigin, float speed, int model, int count )
{
MESSAGE_BEGIN( MSG_PVS, SVC_TEMPENTITY, vecOrigin );
WRITE_BYTE ( TE_EXPLODEMODEL );
WRITE_COORD( vecOrigin.x );
WRITE_COORD( vecOrigin.y );
WRITE_COORD( vecOrigin.z );
WRITE_COORD( speed );
WRITE_SHORT( model );
WRITE_SHORT( count );
WRITE_BYTE ( 15 );// 1.5 seconds
MESSAGE_END();
}
#endif
// called by worldspawn
void W_Precache()
{
// custom items...
// common world objects
UTIL_PrecacheOther( "item_suit" );
UTIL_PrecacheOther( "item_battery" );
UTIL_PrecacheOther( "item_antidote" );
UTIL_PrecacheOther( "item_security" );
UTIL_PrecacheOther( "item_longjump" );
PrecacheWeapons();
UTIL_PrecacheOther( "ammo_buckshot" );
UTIL_PrecacheOther( "ammo_9mmclip" );
UTIL_PrecacheOther( "ammo_9mmAR" );
UTIL_PrecacheOther( "ammo_ARgrenades" );
UTIL_PrecacheOther( "ammo_357" );
UTIL_PrecacheOther( "ammo_gaussclip" );
UTIL_PrecacheOther( "ammo_rpgclip" );
UTIL_PrecacheOther( "ammo_crossbow" );
#if USE_OPFOR
UTIL_PrecacheOther( "ammo_762" );
UTIL_PrecacheOther( "ammo_556" );
#endif
if ( g_pGameRules->IsMultiplayer() )
{
UTIL_PrecacheOther( "weaponbox" );// container for dropped deathmatch weapons
}
g_sModelIndexFireball = PRECACHE_MODEL ("sprites/zerogxplode.spr");// fireball
g_sModelIndexWExplosion = PRECACHE_MODEL ("sprites/WXplo1.spr");// underwater fireball
g_sModelIndexSmoke = PRECACHE_MODEL ("sprites/steam1.spr");// smoke
g_sModelIndexBubbles = PRECACHE_MODEL ( BUBBLES_MODEL );//bubbles
g_sModelIndexBloodSpray = PRECACHE_MODEL ("sprites/bloodspray.spr"); // initial blood
g_sModelIndexBloodDrop = PRECACHE_MODEL ("sprites/blood.spr"); // splattered blood
g_sModelIndexLaser = PRECACHE_MODEL( (char *)g_pModelNameLaser );
g_sModelIndexLaserDot = PRECACHE_MODEL("sprites/laserdot.spr");
//WARNING!!! this is critical stuff! do not edit this
g_sSoundIndexNullSound = PRECACHE_SOUND("common/null.wav");
g_sModelIndexNullModel = PRECACHE_MODEL("models/null.mdl");
g_sModelIndexErrorModel = PRECACHE_MODEL("models/error.mdl");
g_sModelIndexNullSprite = PRECACHE_MODEL("sprites/null.spr");
g_sModelIndexErrorSprite = PRECACHE_MODEL("sprites/error.spr");
// used by explosions
PRECACHE_MODEL ("models/grenade.mdl");
PRECACHE_MODEL ("sprites/explode1.spr");
PRECACHE_SOUND ("weapons/debris1.wav");// explosion aftermaths
PRECACHE_SOUND ("weapons/debris2.wav");// explosion aftermaths
PRECACHE_SOUND ("weapons/debris3.wav");// explosion aftermaths
PRECACHE_SOUND ("weapons/grenade_hit1.wav");//grenade
PRECACHE_SOUND ("weapons/grenade_hit2.wav");//grenade
PRECACHE_SOUND ("weapons/grenade_hit3.wav");//grenade
PRECACHE_SOUND ("weapons/bullet_hit1.wav"); // hit by bullet
PRECACHE_SOUND ("weapons/bullet_hit2.wav"); // hit by bullet
PRECACHE_SOUND ("items/weapondrop1.wav");// weapon falls to the ground
}
bool bIsMultiplayer()
{
return g_pGameRules->IsMultiplayer();
}
|
<%
import collections
import pwnlib.abi
import pwnlib.constants
import pwnlib.shellcraft
import six
%>
<%docstring>lchown(file, owner, group) -> str
Invokes the syscall lchown.
See 'man 2 lchown' for more information.
Arguments:
file(char*): file
owner(uid_t): owner
group(gid_t): group
Returns:
int
</%docstring>
<%page args="file=0, owner=0, group=0"/>
<%
abi = pwnlib.abi.ABI.syscall()
stack = abi.stack
regs = abi.register_arguments[1:]
allregs = pwnlib.shellcraft.registers.current()
can_pushstr = ['file']
can_pushstr_array = []
argument_names = ['file', 'owner', 'group']
argument_values = [file, owner, group]
# Load all of the arguments into their destination registers / stack slots.
register_arguments = dict()
stack_arguments = collections.OrderedDict()
string_arguments = dict()
dict_arguments = dict()
array_arguments = dict()
syscall_repr = []
for name, arg in zip(argument_names, argument_values):
if arg is not None:
syscall_repr.append('%s=%s' % (name, pwnlib.shellcraft.pretty(arg, False)))
# If the argument itself (input) is a register...
if arg in allregs:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[index] = arg
# The argument is not a register. It is a string value, and we
# are expecting a string value
elif name in can_pushstr and isinstance(arg, (six.binary_type, six.text_type)):
if isinstance(arg, six.text_type):
arg = arg.encode('utf-8')
string_arguments[name] = arg
# The argument is not a register. It is a dictionary, and we are
# expecting K:V paris.
elif name in can_pushstr_array and isinstance(arg, dict):
array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()]
# The arguent is not a register. It is a list, and we are expecting
# a list of arguments.
elif name in can_pushstr_array and isinstance(arg, (list, tuple)):
array_arguments[name] = arg
# The argument is not a register, string, dict, or list.
# It could be a constant string ('O_RDONLY') for an integer argument,
# an actual integer value, or a constant.
else:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[target] = arg
# Some syscalls have different names on various architectures.
# Determine which syscall number to use for the current architecture.
for syscall in ['SYS_lchown']:
if hasattr(pwnlib.constants, syscall):
break
else:
raise Exception("Could not locate any syscalls: %r" % syscalls)
%>
/* lchown(${', '.join(syscall_repr)}) */
%for name, arg in string_arguments.items():
${pwnlib.shellcraft.pushstr(arg, append_null=(b'\x00' not in arg))}
${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)}
%endfor
%for name, arg in array_arguments.items():
${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)}
%endfor
%for name, arg in stack_arguments.items():
${pwnlib.shellcraft.push(arg)}
%endfor
${pwnlib.shellcraft.setregs(register_arguments)}
${pwnlib.shellcraft.syscall(syscall)}
|
; /*****************************************************************************
; * ugBASIC - an isomorphic BASIC language compiler for retrocomputers *
; *****************************************************************************
; * Copyright 2021 Marco Spedaletti (asimov@mclink.it)
; *
; * Licensed under the Apache License, Version 2.0 (the "License");
; * you may not use this file except in compliance with the License.
; * You may obtain a copy of the License at
; *
; * http://www.apache.org/licenses/LICENSE-2.0
; *
; * Unless required by applicable law or agreed to in writing, software
; * distributed under the License is distributed on an "AS IS" BASIS,
; * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; * See the License for the specific language governing permissions and
; * limitations under the License.
; *----------------------------------------------------------------------------
; * Concesso in licenza secondo i termini della Licenza Apache, versione 2.0
; * (la "Licenza"); è proibito usare questo file se non in conformità alla
; * Licenza. Una copia della Licenza è disponibile all'indirizzo:
; *
; * http://www.apache.org/licenses/LICENSE-2.0
; *
; * Se non richiesto dalla legislazione vigente o concordato per iscritto,
; * il software distribuito nei termini della Licenza è distribuito
; * "COSì COM'è", SENZA GARANZIE O CONDIZIONI DI ALCUN TIPO, esplicite o
; * implicite. Consultare la Licenza per il testo specifico che regola le
; * autorizzazioni e le limitazioni previste dalla medesima.
; ****************************************************************************/
;* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
;* *
;* IMAGES ROUTINE FOR EF936X *
;* *
;* by Marco Spedaletti *
;* *
;* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
;--------------
GETIMAGE
LDA CURRENTMODE
CMPA #0
BNE GETIMAGE0X
JMP GETIMAGE0
GETIMAGE0X
CMPA #1
BNE GETIMAGE1X
JMP GETIMAGE1
GETIMAGE1X
CMPA #2
BNE GETIMAGE2X
JMP GETIMAGE2
GETIMAGE2X
CMPA #3
BNE GETIMAGE3X
JMP GETIMAGE3
GETIMAGE3X
CMPA #4
BNE GETIMAGE4X
JMP GETIMAGE4
GETIMAGE4X
RTS
GETIMAGE1
GETIMAGE4
RTS
GETIMAGE0
GETIMAGE2
PSHS Y
LDX BITMAPADDRESS
ANDCC #$FE
LDD <IMAGEY
LSLB
ROLA
LSLB
ROLA
LSLB
ROLA
TFR D, Y
ANDCC #$FE
LDD <IMAGEY
LSLB
ROLA
LSLB
ROLA
LSLB
ROLA
LSLB
ROLA
LSLB
ROLA
LEAY D, Y
TFR Y, D
LEAX D, X
ANDCC #$FE
LDD <IMAGEX
LSRA
RORB
LSRA
RORB
LSRA
RORB
LEAX D, X
PULS Y
LDA ,Y
LSRA
LSRA
LSRA
STA <IMAGEW
LDA 1,Y
STA <IMAGEH
STA <IMAGEH2
LEAY 2,Y
LDA <IMAGEW
LDB <IMAGEH
PSHS X,D
JMP GETIMAGE2Y
GETIMAGE3
PSHS Y
LDD <(IMAGEY)
LSLB
ROLA
ADDD #PLOTVBASE
TFR D, X
LDD , X
TFR D, X
LDB <(IMAGEX+1)
LSRB
LSRB
LEAX B, X
PULS Y
LDA ,Y
LSRA
LSRA
STA <IMAGEW
LDA 1,Y
STA <IMAGEH
STA <IMAGEH2
LEAY 2,Y
LDA <IMAGEW
LDB <IMAGEH
PSHS X,D
JMP GETIMAGE2Y
GETIMAGE2Y
GETIMAGE2YDEF
LDA $a7c0
ORA #$01
STA $a7c0
LDB <IMAGEW
DECB
GETIMAGE2L1
LDA B,X
STA B,Y
DECB
CMPB #0
BGE GETIMAGE2L1
LDB <IMAGEW
LEAY B, Y
LDB CURRENTSL
LEAX B, X
DEC <IMAGEH
LDB <IMAGEH
CMPB #0
BEQ GETIMAGECOMMONE2
LDB <IMAGEW
DECB
JMP GETIMAGE2L1
GETIMAGECOMMONE2
PULS X,D
STA <IMAGEW
STB <IMAGEH
LDA $a7c0
ANDA #$fe
STA $a7c0
LDB <IMAGEW
DECB
GETIMAGE2L12
LDA B,X
STA B,Y
DECB
CMPB #0
BGE GETIMAGE2L12
LDB <IMAGEW
LEAY B, Y
LDB CURRENTSL
LEAX B, X
DEC <IMAGEH
LDB <IMAGEH
CMPB #0
BEQ GETIMAGECOMMONE5
LDB <IMAGEW
DECB
JMP GETIMAGE2L12
GETIMAGECOMMONE5
; LDA CURRENTMODE
; CMPA #3
; BEQ GETIMAGECOMMONE53
; LDU #4
; JMP GETIMAGECOMMONE50
; GETIMAGECOMMONE53
; LDU #16
; JMP GETIMAGECOMMONE50
; GETIMAGECOMMONE50
; LDA #0
; STA $A7DB
; GETIMAGECOMMONE50L1
; LDD ,Y
; LEAY 2,Y
; STB $A7DA
; STA $A7DA
; LEAU -1, U
; CMPU #$FFFF
; BNE GETIMAGECOMMONE50L1
GETIMAGECOMMONE
RTS
|
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "OpenGLDriver.h"
#include "private/backend/DriverApi.h"
#include "private/backend/OpenGLPlatform.h"
#include "CommandStreamDispatcher.h"
#include "OpenGLBlitter.h"
#include "OpenGLDriverFactory.h"
#include "OpenGLProgram.h"
#include "TimerQuery.h"
#include "OpenGLContext.h"
#include <utils/compiler.h>
#include <utils/Log.h>
#include <utils/Panic.h>
#include <utils/Systrace.h>
// To emulate EXT_multisampled_render_to_texture properly we need to be able to copy from
// a non-ms texture to an ms attachment. This is only allowed with OpenGL (not GLES), which
// would be fine for us. However, this is also not trivial to implement in Metal so for now
// we don't want to rely on it.
#define ALLOW_REVERSE_MULTISAMPLE_RESOLVE false
// We can only support this feature on OpenGL ES 3.1+
// Support is currently disabled as we don't need it
#define TEXTURE_2D_MULTISAMPLE_SUPPORTED false
#if defined(__EMSCRIPTEN__)
#define HAS_MAPBUFFERS 0
#else
#define HAS_MAPBUFFERS 1
#endif
#define DEBUG_MARKER_NONE 0
#define DEBUG_MARKER_OPENGL 1
// set to the desired debug marker level
#define DEBUG_MARKER_LEVEL DEBUG_MARKER_NONE
#if DEBUG_MARKER_LEVEL == DEBUG_MARKER_OPENGL
# define DEBUG_MARKER() \
DebugMarker _debug_marker(*this, __PRETTY_FUNCTION__);
#else
# define DEBUG_MARKER()
#endif
using namespace filament::math;
using namespace utils;
namespace filament {
namespace backend {
Driver* OpenGLDriverFactory::create(
OpenGLPlatform* const platform, void* const sharedGLContext) noexcept {
return OpenGLDriver::create(platform, sharedGLContext);
}
} // namespace backend
using namespace backend;
using namespace GLUtils;
// ------------------------------------------------------------------------------------------------
UTILS_NOINLINE
Driver* OpenGLDriver::create(
OpenGLPlatform* const platform, void* const sharedGLContext) noexcept {
assert(platform);
OpenGLPlatform* const ec = platform;
{
// here we check we're on a supported version of GL before initializing the driver
GLint major = 0, minor = 0;
glGetIntegerv(GL_MAJOR_VERSION, &major);
glGetIntegerv(GL_MINOR_VERSION, &minor);
if (UTILS_UNLIKELY(glGetError() != GL_NO_ERROR)) {
PANIC_LOG("Can't get OpenGL version");
cleanup:
ec->terminate();
return {};
}
if (GLES30_HEADERS) {
// we require GLES 3.1 headers, but we support GLES 3.0
if (UTILS_UNLIKELY(!(major >= 3 && minor >= 0))) {
PANIC_LOG("OpenGL ES 3.0 minimum needed (current %d.%d)", major, minor);
goto cleanup;
}
} else if (GL41_HEADERS) {
// we require GL 4.1 headers and minimum version
if (UTILS_UNLIKELY(!((major == 4 && minor >= 1) || major > 4))) {
PANIC_LOG("OpenGL 4.1 minimum needed (current %d.%d)", major, minor);
goto cleanup;
}
}
}
OpenGLDriver* const driver = new OpenGLDriver(ec);
return driver;
}
// ------------------------------------------------------------------------------------------------
OpenGLDriver::DebugMarker::DebugMarker(OpenGLDriver& driver, const char* string) noexcept
: driver(driver) {
const char* const begin = string + sizeof("virtual void filament::OpenGLDriver::") - 1;
const char* const end = strchr(begin, '(');
driver.pushGroupMarker(begin, end - begin);
}
OpenGLDriver::DebugMarker::~DebugMarker() noexcept {
driver.popGroupMarker();
}
// ------------------------------------------------------------------------------------------------
OpenGLDriver::OpenGLDriver(OpenGLPlatform* platform) noexcept
: DriverBase(new ConcreteDispatcher<OpenGLDriver>()),
mHandleArena("Handles", 2U * 1024U * 1024U), // TODO: set the amount in configuration
mSamplerMap(32),
mPlatform(*platform) {
std::fill(mSamplerBindings.begin(), mSamplerBindings.end(), nullptr);
// set a reasonable default value for our stream array
mExternalStreams.reserve(8);
#ifndef NDEBUG
slog.i << "OS version: " << mPlatform.getOSVersion() << io::endl;
#endif
// Initialize the blitter only if we have OES_EGL_image_external_essl3
if (mContext.ext.OES_EGL_image_external_essl3) {
mOpenGLBlitter = new OpenGLBlitter(mContext);
mOpenGLBlitter->init();
mContext.resetProgram();
}
if (mContext.ext.EXT_disjoint_timer_query || GL41_HEADERS) {
// timer queries are available
if (mContext.bugs.dont_use_timer_query && mPlatform.canCreateFence()) {
// however, they don't work well, revert to using fences if we can.
mTimerQueryImpl = new TimerQueryFence(mPlatform);
} else {
mTimerQueryImpl = new TimerQueryNative(mContext);
}
mFrameTimeSupported = true;
} else if (mPlatform.canCreateFence()) {
// no timer queries, but we can use fences
mTimerQueryImpl = new TimerQueryFence(mPlatform);
mFrameTimeSupported = true;
} else {
// no queries, no fences -- that's a problem
mTimerQueryImpl = new TimerQueryFallback();
mFrameTimeSupported = false;
}
}
OpenGLDriver::~OpenGLDriver() noexcept {
delete mOpenGLBlitter;
}
// ------------------------------------------------------------------------------------------------
// Driver interface concrete implementation
// ------------------------------------------------------------------------------------------------
void OpenGLDriver::terminate() {
// wait for the GPU to finish executing all commands
glFinish();
// and make sure to execute all the GpuCommandCompleteOps callbacks
executeGpuCommandsCompleteOps();
// because we called glFinish(), all callbacks should have been executed
assert(mGpuCommandCompleteOps.empty());
for (auto& item : mSamplerMap) {
mContext.unbindSampler(item.second);
glDeleteSamplers(1, &item.second);
}
mSamplerMap.clear();
if (mOpenGLBlitter) {
mOpenGLBlitter->terminate();
}
delete mTimerQueryImpl;
mPlatform.terminate();
}
ShaderModel OpenGLDriver::getShaderModel() const noexcept {
return mContext.getShaderModel();
}
// ------------------------------------------------------------------------------------------------
// Change and track GL state
// ------------------------------------------------------------------------------------------------
void OpenGLDriver::bindTexture(GLuint unit, GLTexture const* t) noexcept {
assert(t != nullptr);
mContext.bindTexture(unit, t->gl.target, t->gl.id, t->gl.targetIndex);
}
void OpenGLDriver::useProgram(OpenGLProgram* p) noexcept {
mContext.useProgram(p->gl.program);
// set-up textures and samplers in the proper TMUs (as specified in setSamplers)
p->use(this);
}
void OpenGLDriver::setRasterStateSlow(RasterState rs) noexcept {
mRasterState = rs;
auto& gl = mContext;
// culling state
switch (rs.culling) {
case CullingMode::NONE:
gl.disable(GL_CULL_FACE);
break;
case CullingMode::FRONT:
gl.cullFace(GL_FRONT);
break;
case CullingMode::BACK:
gl.cullFace(GL_BACK);
break;
case CullingMode::FRONT_AND_BACK:
gl.cullFace(GL_FRONT_AND_BACK);
break;
}
gl.frontFace(rs.inverseFrontFaces ? GL_CW : GL_CCW);
if (rs.culling != CullingMode::NONE) {
gl.enable(GL_CULL_FACE);
}
// blending state
if (!rs.hasBlending()) {
gl.disable(GL_BLEND);
} else {
gl.enable(GL_BLEND);
gl.blendEquation(
getBlendEquationMode(rs.blendEquationRGB),
getBlendEquationMode(rs.blendEquationAlpha));
gl.blendFunction(
getBlendFunctionMode(rs.blendFunctionSrcRGB),
getBlendFunctionMode(rs.blendFunctionSrcAlpha),
getBlendFunctionMode(rs.blendFunctionDstRGB),
getBlendFunctionMode(rs.blendFunctionDstAlpha));
}
// depth test
if (rs.depthFunc == RasterState::DepthFunc::A && !rs.depthWrite) {
gl.disable(GL_DEPTH_TEST);
} else {
gl.enable(GL_DEPTH_TEST);
gl.depthFunc(getDepthFunc(rs.depthFunc));
gl.depthMask(GLboolean(rs.depthWrite));
}
// write masks
gl.colorMask(GLboolean(rs.colorWrite));
// AA
if (rs.alphaToCoverage) {
gl.enable(GL_SAMPLE_ALPHA_TO_COVERAGE);
} else {
gl.disable(GL_SAMPLE_ALPHA_TO_COVERAGE);
}
}
// ------------------------------------------------------------------------------------------------
// Creating driver objects
// ------------------------------------------------------------------------------------------------
// For reference on a 64-bits machine:
// GLFence : 8
// GLIndexBuffer : 12 moderate
// GLSamplerGroup : 16 moderate
// -- less than 16 bytes
// GLRenderPrimitive : 40 many
// GLTexture : 44 moderate
// OpenGLProgram : 40 moderate
// GLRenderTarget : 56 few
// -- less than 64 bytes
// GLVertexBuffer : 208 moderate
// GLStream : 120 few
// GLUniformBuffer : 128 many
// -- less than or equal to 208 bytes
OpenGLDriver::HandleAllocator::HandleAllocator(const utils::HeapArea& area)
: mPool0(area.begin(),
pointermath::add(area.begin(), (1 * area.getSize()) / 16)),
mPool1( pointermath::add(area.begin(), (1 * area.getSize()) / 16),
pointermath::add(area.begin(), (6 * area.getSize()) / 16)),
mPool2( pointermath::add(area.begin(), (6 * area.getSize()) / 16),
area.end()) {
#if 0
// this is useful for development, but too verbose even for debug builds
slog.d << "HwFence: " << sizeof(HwFence) << io::endl;
slog.d << "HwSync: " << sizeof(HwSync) << io::endl;
slog.d << "GLIndexBuffer: " << sizeof(GLIndexBuffer) << io::endl;
slog.d << "GLSamplerGroup: " << sizeof(GLSamplerGroup) << io::endl;
slog.d << "GLRenderPrimitive: " << sizeof(GLRenderPrimitive) << io::endl;
slog.d << "GLTexture: " << sizeof(GLTexture) << io::endl;
slog.d << "OpenGLProgram: " << sizeof(OpenGLProgram) << io::endl;
slog.d << "GLRenderTarget: " << sizeof(GLRenderTarget) << io::endl;
slog.d << "GLVertexBuffer: " << sizeof(GLVertexBuffer) << io::endl;
slog.d << "GLUniformBuffer: " << sizeof(GLUniformBuffer) << io::endl;
slog.d << "GLStream: " << sizeof(GLStream) << io::endl;
#endif
}
void* OpenGLDriver::HandleAllocator::alloc(size_t size, size_t alignment, size_t extra) noexcept {
assert(size <= mPool2.getSize());
if (size <= mPool0.getSize()) return mPool0.alloc(size, 16, extra);
if (size <= mPool1.getSize()) return mPool1.alloc(size, 32, extra);
if (size <= mPool2.getSize()) return mPool2.alloc(size, 32, extra);
return nullptr;
}
void OpenGLDriver::HandleAllocator::free(void* p, size_t size) noexcept {
if (size <= mPool0.getSize()) { mPool0.free(p); return; }
if (size <= mPool1.getSize()) { mPool1.free(p); return; }
if (size <= mPool2.getSize()) { mPool2.free(p); return; }
}
// This is "NOINLINE" because it ends-up generating more code than we'd like because of
// the locking (unfortunately, mHandleArena is accessed from 2 threads)
UTILS_NOINLINE
HandleBase::HandleId OpenGLDriver::allocateHandle(size_t size) noexcept {
void* addr = mHandleArena.alloc(size);
assert(addr);
char* const base = (char *)mHandleArena.getArea().begin();
size_t offset = (char*)addr - base;
return HandleBase::HandleId(offset >> HandleAllocator::MIN_ALIGNMENT_SHIFT);
}
template<typename D, typename ... ARGS>
backend::Handle<D> OpenGLDriver::initHandle(ARGS&& ... args) noexcept {
static_assert(sizeof(D) <= 208, "Handle<> too large");
backend::Handle<D> h{ allocateHandle(sizeof(D)) };
D* addr = handle_cast<D *>(h);
new(addr) D(std::forward<ARGS>(args)...);
#if !defined(NDEBUG) && UTILS_HAS_RTTI
addr->typeId = typeid(D).name();
#endif
return h;
}
template<typename D, typename B, typename ... ARGS>
typename std::enable_if<std::is_base_of<B, D>::value, D>::type*
OpenGLDriver::construct(Handle<B> const& handle, ARGS&& ... args) noexcept {
assert(handle);
D* addr = handle_cast<D *>(const_cast<Handle<B>&>(handle));
// currently we implement construct<> with dtor+ctor, we could use operator= also
// but all our dtors are trivial, ~D() is actually a noop.
addr->~D();
new(addr) D(std::forward<ARGS>(args)...);
#if !defined(NDEBUG) && UTILS_HAS_RTTI
addr->typeId = typeid(D).name();
#endif
return addr;
}
template <typename B, typename D, typename>
void OpenGLDriver::destruct(Handle<B>& handle, D const* p) noexcept {
// allow to destroy the nullptr, similarly to operator delete
if (p) {
#if !defined(NDEBUG) && UTILS_HAS_RTTI
if (UTILS_UNLIKELY(p->typeId != typeid(D).name())) {
slog.e << "Destroying handle " << handle.getId() << ", type " << typeid(D).name()
<< ", but handle's actual type is " << p->typeId << io::endl;
std::terminate();
}
const_cast<D *>(p)->typeId = "(deleted)";
#endif
p->~D();
mHandleArena.free(const_cast<D*>(p), sizeof(D));
}
}
Handle<HwVertexBuffer> OpenGLDriver::createVertexBufferS() noexcept {
return initHandle<GLVertexBuffer>();
}
Handle<HwIndexBuffer> OpenGLDriver::createIndexBufferS() noexcept {
return initHandle<GLIndexBuffer>();
}
Handle<HwRenderPrimitive> OpenGLDriver::createRenderPrimitiveS() noexcept {
return initHandle<GLRenderPrimitive>();
}
Handle<HwProgram> OpenGLDriver::createProgramS() noexcept {
return initHandle<OpenGLProgram>();
}
Handle<HwSamplerGroup> OpenGLDriver::createSamplerGroupS() noexcept {
return initHandle<GLSamplerGroup>();
}
Handle<HwUniformBuffer> OpenGLDriver::createUniformBufferS() noexcept {
return initHandle<GLUniformBuffer>();
}
Handle<HwTexture> OpenGLDriver::createTextureS() noexcept {
return initHandle<GLTexture>();
}
Handle<HwTexture> OpenGLDriver::createTextureSwizzledS() noexcept {
return initHandle<GLTexture>();
}
Handle<HwTexture> OpenGLDriver::importTextureS() noexcept {
return initHandle<GLTexture>();
}
Handle<HwRenderTarget> OpenGLDriver::createDefaultRenderTargetS() noexcept {
return initHandle<GLRenderTarget>();
}
Handle<HwRenderTarget> OpenGLDriver::createRenderTargetS() noexcept {
return initHandle<GLRenderTarget>();
}
Handle<HwFence> OpenGLDriver::createFenceS() noexcept {
return initHandle<HwFence>();
}
Handle<HwSync> OpenGLDriver::createSyncS() noexcept {
return initHandle<GLSync>();
}
Handle<HwSwapChain> OpenGLDriver::createSwapChainS() noexcept {
return initHandle<HwSwapChain>();
}
Handle<HwSwapChain> OpenGLDriver::createSwapChainHeadlessS() noexcept {
return initHandle<HwSwapChain>();
}
Handle<HwStream> OpenGLDriver::createStreamFromTextureIdS() noexcept {
return initHandle<GLStream>();
}
Handle<HwTimerQuery> OpenGLDriver::createTimerQueryS() noexcept {
return initHandle<GLTimerQuery>();
}
void OpenGLDriver::createVertexBufferR(
Handle<HwVertexBuffer> vbh,
uint8_t bufferCount,
uint8_t attributeCount,
uint32_t elementCount,
AttributeArray attributes,
BufferUsage usage) {
DEBUG_MARKER()
auto& gl = mContext;
GLVertexBuffer* vb = construct<GLVertexBuffer>(vbh,
bufferCount, attributeCount, elementCount, attributes);
GLsizei n = GLsizei(vb->bufferCount);
assert(n <= (GLsizei)vb->gl.buffers.size());
glGenBuffers(n, vb->gl.buffers.data());
for (GLsizei i = 0; i < n; i++) {
// figure out the size needed for each buffer
size_t size = 0;
for (auto const& item : attributes) {
if (item.buffer == i) {
size_t end = item.offset + elementCount * item.stride;
size = std::max(size, end);
}
}
gl.bindBuffer(GL_ARRAY_BUFFER, vb->gl.buffers[i]);
glBufferData(GL_ARRAY_BUFFER, size, nullptr, getBufferUsage(usage));
}
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::createIndexBufferR(
Handle<HwIndexBuffer> ibh,
ElementType elementType,
uint32_t indexCount,
BufferUsage usage) {
DEBUG_MARKER()
auto& gl = mContext;
uint8_t elementSize = static_cast<uint8_t>(getElementTypeSize(elementType));
GLIndexBuffer* ib = construct<GLIndexBuffer>(ibh, elementSize, indexCount);
glGenBuffers(1, &ib->gl.buffer);
GLsizeiptr size = elementSize * indexCount;
gl.bindVertexArray(nullptr);
gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib->gl.buffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, nullptr, getBufferUsage(usage));
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::createRenderPrimitiveR(Handle<HwRenderPrimitive> rph, int) {
DEBUG_MARKER()
GLRenderPrimitive* rp = handle_cast<GLRenderPrimitive*>(rph);
glGenVertexArrays(1, &rp->gl.vao);
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::createProgramR(Handle<HwProgram> ph, Program&& program) {
DEBUG_MARKER()
construct<OpenGLProgram>(ph, this, program);
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::createSamplerGroupR(Handle<HwSamplerGroup> sbh, size_t size) {
DEBUG_MARKER()
construct<GLSamplerGroup>(sbh, size);
}
void OpenGLDriver::createUniformBufferR(
Handle<HwUniformBuffer> ubh,
size_t size,
BufferUsage usage) {
DEBUG_MARKER()
auto& gl = mContext;
GLUniformBuffer* ub = construct<GLUniformBuffer>(ubh, size, usage);
glGenBuffers(1, &ub->gl.ubo.id);
gl.bindBuffer(GL_UNIFORM_BUFFER, ub->gl.ubo.id);
glBufferData(GL_UNIFORM_BUFFER, size, nullptr, getBufferUsage(usage));
CHECK_GL_ERROR(utils::slog.e)
}
UTILS_NOINLINE
void OpenGLDriver::textureStorage(OpenGLDriver::GLTexture* t,
uint32_t width, uint32_t height, uint32_t depth) noexcept {
auto& gl = mContext;
bindTexture(OpenGLContext::MAX_TEXTURE_UNIT_COUNT - 1, t);
gl.activeTexture(OpenGLContext::MAX_TEXTURE_UNIT_COUNT - 1);
switch (t->gl.target) {
case GL_TEXTURE_2D:
case GL_TEXTURE_CUBE_MAP:
glTexStorage2D(t->gl.target, GLsizei(t->levels), t->gl.internalFormat,
GLsizei(width), GLsizei(height));
break;
case GL_TEXTURE_2D_ARRAY: {
glTexStorage3D(t->gl.target, GLsizei(t->levels), t->gl.internalFormat,
GLsizei(width), GLsizei(height), GLsizei(depth));
break;
}
case GL_TEXTURE_2D_MULTISAMPLE:
if (TEXTURE_2D_MULTISAMPLE_SUPPORTED) {
// NOTE: if there is a mix of texture and renderbuffers, "fixed_sample_locations" must be true
// NOTE: what's the benefit of setting "fixed_sample_locations" to false?
#if GLES31_HEADERS
// only supported from GL 4.3 and GLES 3.1
glTexStorage2DMultisample(t->gl.target, t->samples, t->gl.internalFormat,
GLsizei(width), GLsizei(height), GL_TRUE);
#elif GL41_HEADERS
// only supported in GL (GL4.1 doesn't support glTexStorage2DMultisample)
glTexImage2DMultisample(t->gl.target, t->samples, t->gl.internalFormat,
GLsizei(width), GLsizei(height), GL_TRUE);
#endif
} else {
PANIC_LOG("GL_TEXTURE_2D_MULTISAMPLE is not supported");
}
break;
default: // cannot happen
break;
}
// textureStorage can be used to reallocate the texture at a new size
t->width = width;
t->height = height;
t->depth = depth;
}
void OpenGLDriver::createTextureR(Handle<HwTexture> th, SamplerType target, uint8_t levels,
TextureFormat format, uint8_t samples, uint32_t w, uint32_t h, uint32_t depth,
TextureUsage usage) {
DEBUG_MARKER()
auto& gl = mContext;
GLTexture* t = construct<GLTexture>(th, target, levels, samples, w, h, depth, format, usage);
if (UTILS_LIKELY(usage & TextureUsage::SAMPLEABLE)) {
if (UTILS_UNLIKELY(t->target == SamplerType::SAMPLER_EXTERNAL)) {
mPlatform.createExternalImageTexture(t);
} else {
glGenTextures(1, &t->gl.id);
t->gl.internalFormat = getInternalFormat(format);
assert(t->gl.internalFormat);
// We DO NOT update targetIndex at function exit to take advantage of the fact that
// getIndexForTextureTarget() is constexpr -- so all of this disappears at compile time.
switch (target) {
case SamplerType::SAMPLER_EXTERNAL:
// we can't be here -- doesn't mater what we do
case SamplerType::SAMPLER_2D:
t->gl.target = GL_TEXTURE_2D;
t->gl.targetIndex = (uint8_t)
gl.getIndexForTextureTarget(GL_TEXTURE_2D);
break;
case SamplerType::SAMPLER_2D_ARRAY:
t->gl.target = GL_TEXTURE_2D_ARRAY;
t->gl.targetIndex = (uint8_t)
gl.getIndexForTextureTarget(GL_TEXTURE_2D_ARRAY);
break;
case SamplerType::SAMPLER_CUBEMAP:
t->gl.target = GL_TEXTURE_CUBE_MAP;
t->gl.targetIndex = (uint8_t)
gl.getIndexForTextureTarget(GL_TEXTURE_CUBE_MAP);
break;
}
if (t->samples > 1) {
// Note: we can't be here in practice because filament's user API doesn't
// allow the creation of multi-sampled textures.
if (gl.features.multisample_texture) {
// multi-sample texture on GL 3.2 / GLES 3.1 and above
t->gl.target = GL_TEXTURE_2D_MULTISAMPLE;
t->gl.targetIndex = (uint8_t)
gl.getIndexForTextureTarget(GL_TEXTURE_2D_MULTISAMPLE);
} else {
// Turn off multi-sampling for that texture. It's just not supported.
}
}
textureStorage(t, w, h, depth);
}
} else {
assert(any(usage & (
TextureUsage::COLOR_ATTACHMENT |
TextureUsage::DEPTH_ATTACHMENT |
TextureUsage::STENCIL_ATTACHMENT)));
assert(levels == 1);
assert(target == SamplerType::SAMPLER_2D);
t->gl.internalFormat = getInternalFormat(format);
t->gl.target = GL_RENDERBUFFER;
glGenRenderbuffers(1, &t->gl.id);
renderBufferStorage(t->gl.id, t->gl.internalFormat, w, h, samples);
}
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::createTextureSwizzledR(Handle<HwTexture> th,
SamplerType target, uint8_t levels, TextureFormat format, uint8_t samples,
uint32_t w, uint32_t h, uint32_t depth, TextureUsage usage,
TextureSwizzle r, TextureSwizzle g, TextureSwizzle b, TextureSwizzle a) {
DEBUG_MARKER()
assert(uint8_t(usage) & uint8_t(TextureUsage::SAMPLEABLE));
createTextureR(th, target, levels, format, samples, w, h, depth, usage);
// WebGL does not support swizzling. We assert for this in the Texture builder,
// so it is probably fine to silently ignore the swizzle state here.
#if !defined(__EMSCRIPTEN__)
// the texture is still bound and active from createTextureR
GLTexture* t = handle_cast<GLTexture *>(th);
glTexParameteri(t->gl.target, GL_TEXTURE_SWIZZLE_R, getSwizzleChannel(r));
glTexParameteri(t->gl.target, GL_TEXTURE_SWIZZLE_G, getSwizzleChannel(g));
glTexParameteri(t->gl.target, GL_TEXTURE_SWIZZLE_B, getSwizzleChannel(b));
glTexParameteri(t->gl.target, GL_TEXTURE_SWIZZLE_A, getSwizzleChannel(a));
#endif
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::importTextureR(Handle<HwTexture> th, intptr_t id,
SamplerType target, uint8_t levels, TextureFormat format, uint8_t samples,
uint32_t w, uint32_t h, uint32_t depth, TextureUsage usage) {
DEBUG_MARKER()
auto& gl = mContext;
GLTexture* t = construct<GLTexture>(th, target, levels, samples, w, h, depth, format, usage);
t->gl.id = (GLuint)id;
t->gl.imported = true;
t->gl.internalFormat = getInternalFormat(format);
assert(t->gl.internalFormat);
// We DO NOT update targetIndex at function exit to take advantage of the fact that
// getIndexForTextureTarget() is constexpr -- so all of this disappears at compile time.
switch (target) {
case SamplerType::SAMPLER_EXTERNAL:
t->gl.target = GL_TEXTURE_EXTERNAL_OES;
t->gl.targetIndex = (uint8_t)gl.getIndexForTextureTarget(GL_TEXTURE_EXTERNAL_OES);
break;
case SamplerType::SAMPLER_2D:
t->gl.target = GL_TEXTURE_2D;
t->gl.targetIndex = (uint8_t)gl.getIndexForTextureTarget(GL_TEXTURE_2D);
break;
case SamplerType::SAMPLER_2D_ARRAY:
t->gl.target = GL_TEXTURE_2D_ARRAY;
t->gl.targetIndex = (uint8_t)gl.getIndexForTextureTarget(GL_TEXTURE_2D_ARRAY);
break;
case SamplerType::SAMPLER_CUBEMAP:
t->gl.target = GL_TEXTURE_CUBE_MAP;
t->gl.targetIndex = (uint8_t)gl.getIndexForTextureTarget(GL_TEXTURE_CUBE_MAP);
break;
}
if (t->samples > 1) {
// Note: we can't be here in practice because filament's user API doesn't
// allow the creation of multi-sampled textures.
if (gl.features.multisample_texture) {
// multi-sample texture on GL 3.2 / GLES 3.1 and above
t->gl.target = GL_TEXTURE_2D_MULTISAMPLE;
t->gl.targetIndex = (uint8_t)gl.getIndexForTextureTarget(GL_TEXTURE_2D_MULTISAMPLE);
} else {
// Turn off multi-sampling for that texture. It's just not supported.
}
}
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::framebufferTexture(backend::TargetBufferInfo const& binfo,
GLRenderTarget const* rt, GLenum attachment) noexcept {
#if !defined(NDEBUG)
// Only used by assert() checks below
UTILS_UNUSED_IN_RELEASE auto valueForLevel = [](size_t level, size_t value) {
return std::max(size_t(1), value >> level);
};
#endif
GLTexture* t = handle_cast<GLTexture*>(binfo.handle);
assert(t->target != SamplerType::SAMPLER_EXTERNAL);
assert(rt->width <= valueForLevel(binfo.level, t->width) &&
rt->height <= valueForLevel(binfo.level, t->height));
auto& gl = mContext;
if (any(t->usage & TextureUsage::SAMPLEABLE)) {
GLenum target = GL_TEXTURE_2D;
switch (t->target) {
case SamplerType::SAMPLER_2D:
case SamplerType::SAMPLER_2D_ARRAY:
// this could be GL_TEXTURE_2D_MULTISAMPLE or GL_TEXTURE_2D_ARRAY
target = t->gl.target;
// note: multi-sampled textures can't have mipmaps
break;
case SamplerType::SAMPLER_CUBEMAP:
target = getCubemapTarget(binfo.face);
// note: cubemaps can't be multi-sampled
break;
default:
break;
}
if (rt->gl.samples <= 1 ||
(rt->gl.samples > 1 && t->samples > 1 && gl.features.multisample_texture)) {
// on GL3.2 / GLES3.1 and above multisample is handled when creating the texture.
// If multisampled textures are not supported and we end-up here, things should
// still work, albeit without MSAA.
gl.bindFramebuffer(GL_FRAMEBUFFER, rt->gl.fbo);
switch (target) {
case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
case GL_TEXTURE_2D:
case GL_TEXTURE_2D_MULTISAMPLE:
glFramebufferTexture2D(GL_FRAMEBUFFER, attachment,
target, t->gl.id, binfo.level);
break;
case GL_TEXTURE_2D_ARRAY:
// GL_TEXTURE_2D_MULTISAMPLE_ARRAY is not supported in GLES
glFramebufferTextureLayer(GL_FRAMEBUFFER, attachment,
t->gl.id, binfo.level, binfo.layer);
break;
default:
// we shouldn't be here
break;
}
CHECK_GL_ERROR(utils::slog.e)
} else
#if GLES31_HEADERS
if (gl.ext.EXT_multisampled_render_to_texture && t->depth <= 1) {
assert(rt->gl.samples > 1);
// We have a multi-sample rendertarget and we have EXT_multisampled_render_to_texture,
// so, we can directly use a 1-sample texture as attachment, multi-sample resolve,
// will happen automagically and efficiently in the driver.
// This extension only exists on OpenGL ES.
gl.bindFramebuffer(GL_FRAMEBUFFER, rt->gl.fbo);
glext::glFramebufferTexture2DMultisampleEXT(GL_FRAMEBUFFER,
attachment, target, t->gl.id, binfo.level, rt->gl.samples);
} else
#endif
{ // here we emulate ext.EXT_multisampled_render_to_texture
assert(rt->gl.samples > 1);
// If the texture doesn't already have one, create a sidecar multi-sampled renderbuffer,
// which is where drawing will actually take place, make that our attachment.
gl.bindFramebuffer(GL_FRAMEBUFFER, rt->gl.fbo);
if (t->gl.rb == 0) {
glGenRenderbuffers(1, &t->gl.rb);
renderBufferStorage(t->gl.rb,
t->gl.internalFormat, rt->width, rt->height, rt->gl.samples);
}
glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, t->gl.rb);
// We also need a "read" sidecar fbo, used later for the resolve, which takes place in
// endRenderPass().
if (!rt->gl.fbo_read) {
glGenFramebuffers(1, &rt->gl.fbo_read);
}
gl.bindFramebuffer(GL_FRAMEBUFFER, rt->gl.fbo_read);
switch (target) {
case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
case GL_TEXTURE_2D:
glFramebufferTexture2D(GL_FRAMEBUFFER, attachment,
target, t->gl.id, binfo.level);
break;
case GL_TEXTURE_2D_ARRAY:
glFramebufferTextureLayer(GL_FRAMEBUFFER, attachment,
t->gl.id, binfo.level, binfo.layer);
break;
default:
// we shouldn't be here
break;
}
CHECK_GL_ERROR(utils::slog.e)
switch (attachment) {
case GL_COLOR_ATTACHMENT0:
rt->gl.resolve |= TargetBufferFlags::COLOR0;
break;
case GL_COLOR_ATTACHMENT1:
rt->gl.resolve |= TargetBufferFlags::COLOR1;
break;
case GL_COLOR_ATTACHMENT2:
rt->gl.resolve |= TargetBufferFlags::COLOR2;
break;
case GL_COLOR_ATTACHMENT3:
rt->gl.resolve |= TargetBufferFlags::COLOR3;
break;
case GL_DEPTH_ATTACHMENT:
rt->gl.resolve |= TargetBufferFlags::DEPTH;
break;
case GL_STENCIL_ATTACHMENT:
rt->gl.resolve |= TargetBufferFlags::STENCIL;
break;
case GL_DEPTH_STENCIL_ATTACHMENT:
rt->gl.resolve |= TargetBufferFlags::DEPTH;
rt->gl.resolve |= TargetBufferFlags::STENCIL;
break;
default:
break;
}
}
// In a sense, drawing to a texture level is similar to calling setTextureData on it; in
// both cases, we update the base/max LOD to give shaders access to levels as they become
// available.
updateTextureLodRange(t, binfo.level);
} else {
assert(std::max(uint8_t(1), t->samples) == std::max(uint8_t(1), rt->gl.samples));
gl.bindFramebuffer(GL_FRAMEBUFFER, rt->gl.fbo);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, t->gl.id);
}
CHECK_GL_ERROR(utils::slog.e)
CHECK_GL_FRAMEBUFFER_STATUS(utils::slog.e)
}
void OpenGLDriver::renderBufferStorage(GLuint rbo, GLenum internalformat, uint32_t width,
uint32_t height, uint8_t samples) const noexcept {
glBindRenderbuffer(GL_RENDERBUFFER, rbo);
if (samples > 1) {
// We don't support "implicit" (i.e. EXT_multisampled_render_to_texture) renderbuffer
// (in practice this means that a texture must be marked 'SAMPLEABLE' if 'implicit'
// resolves are desired.
glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, internalformat, width, height);
} else {
glRenderbufferStorage(GL_RENDERBUFFER, internalformat, width, height);
}
// unbind the renderbuffer, to avoid any later confusion
glBindRenderbuffer(GL_RENDERBUFFER, 0);
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::createDefaultRenderTargetR(
Handle<HwRenderTarget> rth, int) {
DEBUG_MARKER()
construct<GLRenderTarget>(rth, 0, 0); // FIXME: we don't know the width/height
uint32_t framebuffer = 0;
uint32_t colorbuffer = 0;
uint32_t depthbuffer = 0;
mPlatform.createDefaultRenderTarget(framebuffer, colorbuffer, depthbuffer);
GLRenderTarget* rt = handle_cast<GLRenderTarget*>(rth);
rt->gl.fbo = framebuffer;
rt->gl.samples = 1;
// FIXME: these flags should reflect the actual attachments present
rt->targets = TargetBufferFlags::COLOR0 | TargetBufferFlags::DEPTH;
}
void OpenGLDriver::createRenderTargetR(Handle<HwRenderTarget> rth,
TargetBufferFlags targets,
uint32_t width,
uint32_t height,
uint8_t samples,
backend::MRT color,
TargetBufferInfo depth,
TargetBufferInfo stencil) {
DEBUG_MARKER()
GLRenderTarget* rt = construct<GLRenderTarget>(rth, width, height);
glGenFramebuffers(1, &rt->gl.fbo);
/*
* The GLES 3.0 spec states:
*
* --------------
*
* GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE is returned
* - if the value of GL_RENDERBUFFER_SAMPLES is not the same for all attached renderbuffers or,
* - if the attached images are a mix of renderbuffers and textures,
* the value of GL_RENDERBUFFER_SAMPLES is not zero.
*
* GLES 3.1 (spec, refpages are wrong) and EXT_multisampled_render_to_texture add:
*
* The value of RENDERBUFFER_SAMPLES is the same for all
* attached renderbuffers; the value of TEXTURE_SAMPLES
* is the same for all texture attachments; and, if the attached
* images are a mix of renderbuffers and textures, the value of
* RENDERBUFFER_SAMPLES matches the value of TEXTURE_SAMPLES.
*
*
* In other words, heterogeneous (renderbuffer/textures) attachments are not supported in
* GLES3.0, unless EXT_multisampled_render_to_texture is present.
*
* 'features.multisample_texture' below is a proxy for "GLES3.1 or GL4.x".
*
* --------------
*
* About the size of the attachments:
*
* If the attachment sizes are not all identical, the results of rendering are defined only
* within the largest area that can fit in all of the attachments. This area is defined as
* the intersection of rectangles having a lower left of (0, 0) and an upper right of
* (width, height) for each attachment. Contents of attachments outside this area are
* undefined after execution of a rendering command.
*/
rt->gl.samples = samples;
rt->targets = targets;
if (any(targets & TargetBufferFlags::COLOR_ALL)) {
GLenum bufs[4] = { GL_NONE };
for (size_t i = 0; i < 4; i++) {
if (any(targets & getMRTColorFlag(i))) {
rt->gl.color[i].texture = handle_cast<GLTexture*>(color[i].handle);
rt->gl.color[i].level = color[i].level;
framebufferTexture(color[i], rt, GL_COLOR_ATTACHMENT0 + i);
bufs[i] = GL_COLOR_ATTACHMENT0 + i;
}
}
glDrawBuffers(4, bufs);
CHECK_GL_ERROR(utils::slog.e)
}
// handle special cases first (where depth/stencil are packed)
bool specialCased = false;
if ((targets & TargetBufferFlags::DEPTH_AND_STENCIL) == TargetBufferFlags::DEPTH_AND_STENCIL) {
assert(!stencil.handle || stencil.handle == depth.handle);
rt->gl.depth.texture = handle_cast<GLTexture*>(depth.handle);
rt->gl.depth.level = depth.level;
if (any(rt->gl.depth.texture->usage & TextureUsage::SAMPLEABLE) ||
(!depth.handle && !stencil.handle)) {
// special case: depth & stencil requested, and both provided as the same texture
// special case: depth & stencil requested, but both not provided
specialCased = true;
framebufferTexture(depth, rt, GL_DEPTH_STENCIL_ATTACHMENT);
}
}
if (!specialCased) {
if (any(targets & TargetBufferFlags::DEPTH)) {
rt->gl.depth.texture = handle_cast<GLTexture*>(depth.handle);
rt->gl.depth.level = depth.level;
framebufferTexture(depth, rt, GL_DEPTH_ATTACHMENT);
}
if (any(targets & TargetBufferFlags::STENCIL)) {
rt->gl.stencil.texture = handle_cast<GLTexture*>(stencil.handle);
rt->gl.stencil.level = stencil.level;
framebufferTexture(stencil, rt, GL_STENCIL_ATTACHMENT);
}
}
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::createFenceR(Handle<HwFence> fh, int) {
DEBUG_MARKER()
HwFence* f = handle_cast<HwFence*>(fh);
f->fence = mPlatform.createFence();
}
void OpenGLDriver::createSyncR(Handle<HwSync> fh, int) {
DEBUG_MARKER()
GLSync* f = handle_cast<GLSync *>(fh);
f->gl.sync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
CHECK_GL_ERROR(utils::slog.e)
// check the status of the sync once a frame, since we must do this from our thread
std::weak_ptr<GLSync::State> weak = f->result;
runEveryNowAndThen([sync = f->gl.sync, weak]() -> bool {
auto result = weak.lock();
if (result) {
GLenum status = glClientWaitSync(sync, 0, 0u);
result->status.store(status, std::memory_order_relaxed);
return (status != GL_TIMEOUT_EXPIRED);
}
return true; // we're done
});
}
void OpenGLDriver::createSwapChainR(Handle<HwSwapChain> sch, void* nativeWindow, uint64_t flags) {
DEBUG_MARKER()
HwSwapChain* sc = handle_cast<HwSwapChain*>(sch);
sc->swapChain = mPlatform.createSwapChain(nativeWindow, flags);
}
void OpenGLDriver::createSwapChainHeadlessR(Handle<HwSwapChain> sch,
uint32_t width, uint32_t height, uint64_t flags) {
DEBUG_MARKER()
HwSwapChain* sc = handle_cast<HwSwapChain*>(sch);
sc->swapChain = mPlatform.createSwapChain(width, height, flags);
}
void OpenGLDriver::createStreamFromTextureIdR(Handle<HwStream> sh,
intptr_t externalTextureId, uint32_t width, uint32_t height) {
DEBUG_MARKER()
GLStream* s = handle_cast<GLStream*>(sh);
// It would be better if we could query the externalTextureId size, unfortunately
// this is not supported in GL for GL_TEXTURE_EXTERNAL_OES targets
s->width = width;
s->height = height;
s->gl.externalTextureId = static_cast<GLuint>(externalTextureId);
s->streamType = StreamType::TEXTURE_ID;
glGenTextures(GLStream::ROUND_ROBIN_TEXTURE_COUNT, s->user_thread.read);
glGenTextures(GLStream::ROUND_ROBIN_TEXTURE_COUNT, s->user_thread.write);
for (auto& info : s->user_thread.infos) {
info.ets = mPlatform.createExternalTextureStorage();
}
}
void OpenGLDriver::createTimerQueryR(Handle<HwTimerQuery> tqh, int) {
DEBUG_MARKER()
GLTimerQuery* tq = handle_cast<GLTimerQuery*>(tqh);
glGenQueries(1u, &tq->gl.query);
CHECK_GL_ERROR(utils::slog.e)
}
// ------------------------------------------------------------------------------------------------
// Destroying driver objects
// ------------------------------------------------------------------------------------------------
void OpenGLDriver::destroyVertexBuffer(Handle<HwVertexBuffer> vbh) {
DEBUG_MARKER()
if (vbh) {
auto& gl = mContext;
GLVertexBuffer const* eb = handle_cast<const GLVertexBuffer*>(vbh);
GLsizei n = GLsizei(eb->bufferCount);
auto& buffers = eb->gl.buffers;
gl.deleteBuffers(n, buffers.data(), GL_ARRAY_BUFFER);
destruct(vbh, eb);
}
}
void OpenGLDriver::destroyIndexBuffer(Handle<HwIndexBuffer> ibh) {
DEBUG_MARKER()
if (ibh) {
auto& gl = mContext;
GLIndexBuffer const* ib = handle_cast<const GLIndexBuffer*>(ibh);
gl.deleteBuffers(1, &ib->gl.buffer, GL_ELEMENT_ARRAY_BUFFER);
destruct(ibh, ib);
}
}
void OpenGLDriver::destroyRenderPrimitive(Handle<HwRenderPrimitive> rph) {
DEBUG_MARKER()
if (rph) {
auto& gl = mContext;
GLRenderPrimitive const* rp = handle_cast<const GLRenderPrimitive*>(rph);
gl.deleteVextexArrays(1, &rp->gl.vao);
destruct(rph, rp);
}
}
void OpenGLDriver::destroyProgram(Handle<HwProgram> ph) {
DEBUG_MARKER()
if (ph) {
OpenGLProgram* p = handle_cast<OpenGLProgram*>(ph);
destruct(ph, p);
}
}
void OpenGLDriver::destroySamplerGroup(Handle<HwSamplerGroup> sbh) {
DEBUG_MARKER()
if (sbh) {
GLSamplerGroup* sb = handle_cast<GLSamplerGroup*>(sbh);
destruct(sbh, sb);
}
}
void OpenGLDriver::destroyUniformBuffer(Handle<HwUniformBuffer> ubh) {
DEBUG_MARKER()
if (ubh) {
auto& gl = mContext;
GLUniformBuffer* ub = handle_cast<GLUniformBuffer*>(ubh);
gl.deleteBuffers(1, &ub->gl.ubo.id, GL_UNIFORM_BUFFER);
destruct(ubh, ub);
}
}
void OpenGLDriver::destroyTexture(Handle<HwTexture> th) {
DEBUG_MARKER()
if (th) {
GLTexture* t = handle_cast<GLTexture*>(th);
if (UTILS_LIKELY(!t->gl.imported)) {
auto& gl = mContext;
if (UTILS_LIKELY(t->usage & TextureUsage::SAMPLEABLE)) {
gl.unbindTexture(t->gl.target, t->gl.id);
if (UTILS_UNLIKELY(t->hwStream)) {
detachStream(t);
}
if (t->gl.rb) {
glDeleteRenderbuffers(1, &t->gl.rb);
}
if (UTILS_UNLIKELY(t->target == SamplerType::SAMPLER_EXTERNAL)) {
mPlatform.destroyExternalImage(t);
} else {
glDeleteTextures(1, &t->gl.id);
}
} else {
assert(t->gl.target == GL_RENDERBUFFER);
assert(t->gl.rb == 0);
glDeleteRenderbuffers(1, &t->gl.id);
}
if (t->gl.fence) {
glDeleteSync(t->gl.fence);
}
}
destruct(th, t);
}
}
void OpenGLDriver::destroyRenderTarget(Handle<HwRenderTarget> rth) {
DEBUG_MARKER()
if (rth) {
auto& gl = mContext;
GLRenderTarget* rt = handle_cast<GLRenderTarget*>(rth);
if (rt->gl.fbo) {
// first unbind this framebuffer if needed
gl.bindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, &rt->gl.fbo);
}
if (rt->gl.fbo_read) {
// first unbind this framebuffer if needed
gl.bindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, &rt->gl.fbo_read);
}
destruct(rth, rt);
}
}
void OpenGLDriver::destroySwapChain(Handle<HwSwapChain> sch) {
DEBUG_MARKER()
if (sch) {
HwSwapChain* sc = handle_cast<HwSwapChain*>(sch);
mPlatform.destroySwapChain(sc->swapChain);
destruct(sch, sc);
}
}
void OpenGLDriver::destroyStream(Handle<HwStream> sh) {
DEBUG_MARKER()
if (sh) {
GLStream* s = handle_cast<GLStream*>(sh);
// if this stream is still attached to a texture, detach it first
auto& externalStreams = mExternalStreams;
auto pos = std::find_if(externalStreams.begin(), externalStreams.end(),
[s](GLTexture const* t) { return t->hwStream == s; });
if (pos != externalStreams.end()) {
detachStream(*pos);
}
if (s->streamType == StreamType::NATIVE) {
mPlatform.destroyStream(s->stream);
} else if (s->streamType == StreamType::TEXTURE_ID) {
glDeleteTextures(GLStream::ROUND_ROBIN_TEXTURE_COUNT, s->user_thread.read);
glDeleteTextures(GLStream::ROUND_ROBIN_TEXTURE_COUNT, s->user_thread.write);
if (s->gl.fbo) {
glDeleteFramebuffers(1, &s->gl.fbo);
}
for (auto const& info : s->user_thread.infos) {
mPlatform.destroyExternalTextureStorage(info.ets);
}
}
destruct(sh, s);
}
}
void OpenGLDriver::destroyTimerQuery(Handle<HwTimerQuery> tqh) {
DEBUG_MARKER()
if (tqh) {
GLTimerQuery* tq = handle_cast<GLTimerQuery*>(tqh);
glDeleteQueries(1u, &tq->gl.query);
destruct(tqh, tq);
}
}
void OpenGLDriver::destroySync(Handle<HwSync> sh) {
DEBUG_MARKER()
if (sh) {
GLSync* s = handle_cast<GLSync*>(sh);
glDeleteSync(s->gl.sync);
destruct(sh, s);
}
}
// ------------------------------------------------------------------------------------------------
// Synchronous APIs
// These are called on the application's thread
// ------------------------------------------------------------------------------------------------
Handle<HwStream> OpenGLDriver::createStreamNative(void* nativeStream) {
Platform::Stream* stream = mPlatform.createStream(nativeStream);
return initHandle<GLStream>(stream);
}
Handle<HwStream> OpenGLDriver::createStreamAcquired() {
return initHandle<GLStream>();
}
// Stashes an acquired external image and a release callback. The image is not bound to OpenGL until
// the subsequent call to beginFrame (see updateStreamAcquired).
//
// setAcquiredImage should be called by the user outside of beginFrame / endFrame, and should be
// called only once per frame. If the user pushes images to the same stream multiple times in a
// single frame, we emit a warning and honor only the final image, but still invoke all callbacks.
void OpenGLDriver::setAcquiredImage(Handle<HwStream> sh, void* hwbuffer,
backend::StreamCallback cb, void* userData) {
GLStream* glstream = handle_cast<GLStream*>(sh);
if (glstream->user_thread.pending.image) {
scheduleRelease(std::move(glstream->user_thread.pending));
slog.w << "Acquired image is set more than once per frame." << io::endl;
}
glstream->user_thread.pending = mPlatform.transformAcquiredImage({hwbuffer, cb, userData});
}
void OpenGLDriver::updateStreams(DriverApi* driver) {
if (UTILS_UNLIKELY(!mExternalStreams.empty())) {
OpenGLBlitter::State state;
for (GLTexture* t : mExternalStreams) {
assert(t);
GLStream* s = static_cast<GLStream*>(t->hwStream);
if (UTILS_UNLIKELY(s == nullptr)) {
// this can happen because we're called synchronously and the setExternalStream()
// call may not have been processed yet.
continue;
}
if (s->streamType == StreamType::TEXTURE_ID) {
state.setup();
updateStreamTexId(t, driver);
}
if (s->streamType == StreamType::ACQUIRED) {
updateStreamAcquired(t, driver);
}
}
}
}
void OpenGLDriver::setStreamDimensions(Handle<HwStream> sh, uint32_t width, uint32_t height) {
if (sh) {
GLStream* s = handle_cast<GLStream*>(sh);
s->width = width;
s->height = height;
}
}
int64_t OpenGLDriver::getStreamTimestamp(Handle<HwStream> sh) {
if (sh) {
GLStream* s = handle_cast<GLStream*>(sh);
return s->user_thread.timestamp;
}
return 0;
}
void OpenGLDriver::destroyFence(Handle<HwFence> fh) {
if (fh) {
HwFence* f = handle_cast<HwFence*>(fh);
mPlatform.destroyFence(f->fence);
destruct(fh, f);
}
}
FenceStatus OpenGLDriver::wait(Handle<HwFence> fh, uint64_t timeout) {
if (fh) {
HwFence* f = handle_cast<HwFence*>(fh);
if (f->fence == nullptr) {
// we can end-up here if:
// - the platform doesn't support h/w fences
// - wait() was called before the fence was asynchronously created.
// This case is not handled in OpenGLDriver but is handle by FFence.
// TODO: move FFence logic into the backend.
return FenceStatus::ERROR;
}
return mPlatform.waitFence(f->fence, timeout);
}
return FenceStatus::ERROR;
}
bool OpenGLDriver::isTextureFormatSupported(TextureFormat format) {
auto& gl = mContext;
if (isETC2Compression(format)) {
return gl.ext.texture_compression_etc2;
}
if (isS3TCCompression(format)) {
if (isS3TCSRGBCompression(format)) {
return gl.ext.texture_compression_s3tc && (gl.ext.EXT_texture_sRGB || gl.ext.EXT_texture_compression_s3tc_srgb);
} else {
return gl.ext.texture_compression_s3tc;
}
}
return getInternalFormat(format) != 0;
}
bool OpenGLDriver::isTextureFormatMipmappable(TextureFormat format) {
// The OpenGL spec for GenerateMipmap stipulates that it returns INVALID_OPERATION unless
// the sized internal format is both color-renderable and texture-filterable.
switch (format) {
case TextureFormat::DEPTH16:
case TextureFormat::DEPTH24:
case TextureFormat::DEPTH32F:
case TextureFormat::DEPTH24_STENCIL8:
case TextureFormat::DEPTH32F_STENCIL8:
return false;
default:
return isRenderTargetFormatSupported(format);
}
}
bool OpenGLDriver::isRenderTargetFormatSupported(TextureFormat format) {
// Supported formats per http://docs.gl/es3/glRenderbufferStorage, note that desktop OpenGL may
// support more formats, but it requires querying GL_INTERNALFORMAT_SUPPORTED which is not
// available in OpenGL ES.
auto& gl = mContext;
switch (format) {
// Core formats.
case TextureFormat::R8:
case TextureFormat::R8UI:
case TextureFormat::R8I:
case TextureFormat::STENCIL8:
case TextureFormat::R16UI:
case TextureFormat::R16I:
case TextureFormat::RG8:
case TextureFormat::RG8UI:
case TextureFormat::RG8I:
case TextureFormat::RGB565:
case TextureFormat::RGB5_A1:
case TextureFormat::RGBA4:
case TextureFormat::DEPTH16:
case TextureFormat::RGB8:
case TextureFormat::DEPTH24:
case TextureFormat::R32UI:
case TextureFormat::R32I:
case TextureFormat::RG16UI:
case TextureFormat::RG16I:
case TextureFormat::RGBA8:
case TextureFormat::SRGB8_A8:
case TextureFormat::RGB10_A2:
case TextureFormat::RGBA8UI:
case TextureFormat::RGBA8I:
case TextureFormat::DEPTH32F:
case TextureFormat::DEPTH24_STENCIL8:
case TextureFormat::DEPTH32F_STENCIL8:
case TextureFormat::RG32UI:
case TextureFormat::RG32I:
case TextureFormat::RGBA16UI:
case TextureFormat::RGBA16I:
return true;
// Three-component SRGB is a color-renderable texture format in core OpenGL on desktop.
case TextureFormat::SRGB8:
return GL41_HEADERS;
// Half-float formats, requires extension.
case TextureFormat::R16F:
case TextureFormat::RG16F:
case TextureFormat::RGBA16F:
return gl.ext.EXT_color_buffer_float || gl.ext.EXT_color_buffer_half_float;
// RGB16F is only supported with EXT_color_buffer_half_float
case TextureFormat::RGB16F:
return gl.ext.EXT_color_buffer_half_float;
// Float formats from GL_EXT_color_buffer_float
case TextureFormat::R32F:
case TextureFormat::RG32F:
case TextureFormat::RGBA32F:
return gl.ext.EXT_color_buffer_float;
// RGB_11_11_10 is only supported with some specific extensions
case TextureFormat::R11F_G11F_B10F:
return gl.ext.EXT_color_buffer_float || gl.ext.APPLE_color_buffer_packed_float;
default:
return false;
}
}
bool OpenGLDriver::isFrameTimeSupported() {
return mFrameTimeSupported;
}
// ------------------------------------------------------------------------------------------------
// Swap chains
// ------------------------------------------------------------------------------------------------
void OpenGLDriver::commit(Handle<HwSwapChain> sch) {
DEBUG_MARKER()
HwSwapChain* sc = handle_cast<HwSwapChain*>(sch);
mPlatform.commit(sc->swapChain);
}
void OpenGLDriver::makeCurrent(Handle<HwSwapChain> schDraw, Handle<HwSwapChain> schRead) {
DEBUG_MARKER()
HwSwapChain* scDraw = handle_cast<HwSwapChain*>(schDraw);
HwSwapChain* scRead = handle_cast<HwSwapChain*>(schRead);
mPlatform.makeCurrent(scDraw->swapChain, scRead->swapChain);
}
// ------------------------------------------------------------------------------------------------
// Updating driver objects
// ------------------------------------------------------------------------------------------------
void OpenGLDriver::updateVertexBuffer(Handle<HwVertexBuffer> vbh,
size_t index, BufferDescriptor&& p, uint32_t byteOffset) {
DEBUG_MARKER()
auto& gl = mContext;
GLVertexBuffer* eb = handle_cast<GLVertexBuffer *>(vbh);
gl.bindBuffer(GL_ARRAY_BUFFER, eb->gl.buffers[index]);
glBufferSubData(GL_ARRAY_BUFFER, byteOffset, p.size, p.buffer);
scheduleDestroy(std::move(p));
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::updateIndexBuffer(
Handle<HwIndexBuffer> ibh, BufferDescriptor&& p, uint32_t byteOffset) {
DEBUG_MARKER()
auto& gl = mContext;
GLIndexBuffer* ib = handle_cast<GLIndexBuffer *>(ibh);
assert(ib->elementSize == 2 || ib->elementSize == 4);
gl.bindVertexArray(nullptr);
gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib->gl.buffer);
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, byteOffset, p.size, p.buffer);
scheduleDestroy(std::move(p));
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::loadUniformBuffer(Handle<HwUniformBuffer> ubh, BufferDescriptor&& p) {
DEBUG_MARKER()
GLUniformBuffer* ub = handle_cast<GLUniformBuffer *>(ubh);
auto& gl = mContext;
if (p.size > 0) {
updateBuffer(GL_UNIFORM_BUFFER, &ub->gl.ubo, p,
(uint32_t)gl.gets.uniform_buffer_offset_alignment);
}
scheduleDestroy(std::move(p));
}
void OpenGLDriver::updateBuffer(GLenum target,
GLBuffer* buffer, BufferDescriptor const& p, uint32_t alignment) noexcept {
assert(buffer->capacity >= p.size);
assert(buffer->id);
auto& gl = mContext;
gl.bindBuffer(target, buffer->id);
if (buffer->usage == BufferUsage::STREAM) {
buffer->size = (uint32_t)p.size;
// If MapBufferRange is supported, then attempt to use that instead of BufferSubData, which
// can be quite inefficient on some platforms. Note that WebGL does not support
// MapBufferRange, but we still allow STREAM semantics for the web platform.
if (HAS_MAPBUFFERS) {
uint32_t offset = buffer->base + buffer->size;
offset = (offset + (alignment - 1u)) & ~(alignment - 1u);
if (offset + p.size > buffer->capacity) {
// if we've reached the end of the buffer, we orphan it and allocate a new one.
// this is assuming the driver actually does that as opposed to stalling. This is
// the case for Mali and Adreno -- we could use fences instead.
offset = 0;
glBufferData(target, buffer->capacity, nullptr, getBufferUsage(buffer->usage));
}
retry:
void* vaddr = glMapBufferRange(target, offset, p.size,
GL_MAP_WRITE_BIT |
GL_MAP_INVALIDATE_RANGE_BIT |
GL_MAP_UNSYNCHRONIZED_BIT);
if (vaddr) {
memcpy(vaddr, p.buffer, p.size);
if (glUnmapBuffer(target) == GL_FALSE) {
// According to the spec, UnmapBuffer can return FALSE in rare conditions (e.g.
// during a screen mode change). Note that is not a GL error, and we can handle
// it by simply making a second attempt.
goto retry; // NOLINT(cppcoreguidelines-avoid-goto,hicpp-avoid-goto)
}
} else {
// handle mapping error, revert to glBufferSubData()
glBufferSubData(target, offset, p.size, p.buffer);
}
buffer->base = offset;
CHECK_GL_ERROR(utils::slog.e)
return;
}
}
if (p.size == buffer->capacity) {
// it looks like it's generally faster (or not worse) to use glBufferData()
glBufferData(target, buffer->capacity, p.buffer, getBufferUsage(buffer->usage));
} else {
// when loading less that the buffer size, it's okay to assume the back of the buffer
// is undefined. glBufferSubData() could be catastrophically inefficient if several are
// issued during the same frame. Currently, we're not doing that though.
// TODO: investigate if it'll be faster to use glBufferData().
glBufferSubData(target, 0, p.size, p.buffer);
}
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::updateSamplerGroup(Handle<HwSamplerGroup> sbh,
SamplerGroup&& samplerGroup) {
DEBUG_MARKER()
GLSamplerGroup* sb = handle_cast<GLSamplerGroup *>(sbh);
*sb->sb = std::move(samplerGroup); // NOLINT(performance-move-const-arg)
}
void OpenGLDriver::update2DImage(Handle<HwTexture> th,
uint32_t level, uint32_t xoffset, uint32_t yoffset, uint32_t width, uint32_t height,
PixelBufferDescriptor&& data) {
DEBUG_MARKER()
GLTexture* t = handle_cast<GLTexture *>(th);
if (data.type == PixelDataType::COMPRESSED) {
setCompressedTextureData(t,
level, xoffset, yoffset, 0, width, height, 1, std::move(data), nullptr);
} else {
setTextureData(t,
level, xoffset, yoffset, 0, width, height, 1, std::move(data), nullptr);
}
}
void OpenGLDriver::updateCubeImage(Handle<HwTexture> th, uint32_t level,
PixelBufferDescriptor&& data, FaceOffsets faceOffsets) {
DEBUG_MARKER()
GLTexture* t = handle_cast<GLTexture *>(th);
if (data.type == PixelDataType::COMPRESSED) {
setCompressedTextureData(t, level, 0, 0, 0, 0, 0, 0, std::move(data), &faceOffsets);
} else {
setTextureData(t, level, 0, 0, 0, 0, 0, 0, std::move(data), &faceOffsets);
}
}
void OpenGLDriver::generateMipmaps(Handle<HwTexture> th) {
DEBUG_MARKER()
auto& gl = mContext;
GLTexture* t = handle_cast<GLTexture *>(th);
assert(t->gl.target != GL_TEXTURE_2D_MULTISAMPLE);
// Note: glGenerateMimap can also fail if the internal format is not both
// color-renderable and filterable (i.e.: doesn't work for depth)
bindTexture(OpenGLContext::MAX_TEXTURE_UNIT_COUNT - 1, t);
gl.activeTexture(OpenGLContext::MAX_TEXTURE_UNIT_COUNT - 1);
t->gl.baseLevel = 0;
t->gl.maxLevel = static_cast<uint8_t>(t->levels - 1);
glTexParameteri(t->gl.target, GL_TEXTURE_BASE_LEVEL, t->gl.baseLevel);
glTexParameteri(t->gl.target, GL_TEXTURE_MAX_LEVEL, t->gl.maxLevel);
glGenerateMipmap(t->gl.target);
CHECK_GL_ERROR(utils::slog.e)
}
bool OpenGLDriver::canGenerateMipmaps() {
return true;
}
void OpenGLDriver::setTextureData(GLTexture* t,
uint32_t level,
uint32_t xoffset, uint32_t yoffset, uint32_t zoffset,
uint32_t width, uint32_t height, uint32_t depth,
PixelBufferDescriptor&& p, FaceOffsets const* faceOffsets) {
DEBUG_MARKER()
auto& gl = mContext;
assert(xoffset + width <= t->width >> level);
assert(yoffset + height <= t->height >> level);
assert(zoffset + depth <= t->depth);
assert(t->samples <= 1);
if (UTILS_UNLIKELY(t->gl.target == GL_TEXTURE_EXTERNAL_OES)) {
// this is in fact an external texture, this becomes a no-op.
return;
}
GLenum glFormat = getFormat(p.format);
GLenum glType = getType(p.type);
gl.pixelStore(GL_UNPACK_ROW_LENGTH, p.stride);
gl.pixelStore(GL_UNPACK_ALIGNMENT, p.alignment);
gl.pixelStore(GL_UNPACK_SKIP_PIXELS, p.left);
gl.pixelStore(GL_UNPACK_SKIP_ROWS, p.top);
switch (t->target) {
case SamplerType::SAMPLER_EXTERNAL:
// if we get there, it's because the user is trying to use an external texture
// but it's not supported, so instead, we behave like a texture2d.
// fallthrough...
case SamplerType::SAMPLER_2D:
// NOTE: GL_TEXTURE_2D_MULTISAMPLE is not allowed
bindTexture(OpenGLContext::MAX_TEXTURE_UNIT_COUNT - 1, t);
gl.activeTexture(OpenGLContext::MAX_TEXTURE_UNIT_COUNT - 1);
assert(t->gl.target == GL_TEXTURE_2D);
glTexSubImage2D(t->gl.target, GLint(level),
GLint(xoffset), GLint(yoffset),
width, height, glFormat, glType, p.buffer);
break;
case SamplerType::SAMPLER_2D_ARRAY:
// NOTE: GL_TEXTURE_2D_MULTISAMPLE is not allowed
bindTexture(OpenGLContext::MAX_TEXTURE_UNIT_COUNT - 1, t);
gl.activeTexture(OpenGLContext::MAX_TEXTURE_UNIT_COUNT - 1);
assert(t->gl.target == GL_TEXTURE_2D_ARRAY);
glTexSubImage3D(t->gl.target, GLint(level),
GLint(xoffset), GLint(yoffset), GLint(zoffset),
width, height, depth, glFormat, glType, p.buffer);
break;
case SamplerType::SAMPLER_CUBEMAP: {
assert(t->gl.target == GL_TEXTURE_CUBE_MAP);
bindTexture(OpenGLContext::MAX_TEXTURE_UNIT_COUNT - 1, t);
gl.activeTexture(OpenGLContext::MAX_TEXTURE_UNIT_COUNT - 1);
FaceOffsets const& offsets = *faceOffsets;
#pragma nounroll
for (size_t face = 0; face < 6; face++) {
GLenum target = getCubemapTarget(TextureCubemapFace(face));
glTexSubImage2D(target, GLint(level), 0, 0,
t->width >> level, t->height >> level, glFormat, glType,
static_cast<uint8_t const*>(p.buffer) + offsets[face]);
}
break;
}
}
// update the base/max LOD so we don't access undefined LOD. this allows the app to
// specify levels as they become available.
if (int8_t(level) < t->gl.baseLevel) {
t->gl.baseLevel = int8_t(level);
glTexParameteri(t->gl.target, GL_TEXTURE_BASE_LEVEL, t->gl.baseLevel);
}
if (int8_t(level) > t->gl.maxLevel) {
t->gl.maxLevel = int8_t(level);
glTexParameteri(t->gl.target, GL_TEXTURE_MAX_LEVEL, t->gl.maxLevel);
}
scheduleDestroy(std::move(p));
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::setCompressedTextureData(GLTexture* t, uint32_t level,
uint32_t xoffset, uint32_t yoffset, uint32_t zoffset,
uint32_t width, uint32_t height, uint32_t depth,
PixelBufferDescriptor&& p, FaceOffsets const* faceOffsets) {
DEBUG_MARKER()
auto& gl = mContext;
assert(xoffset + width <= t->width >> level);
assert(yoffset + height <= t->height >> level);
assert(zoffset + depth <= t->depth);
assert(t->samples <= 1);
if (UTILS_UNLIKELY(t->gl.target == GL_TEXTURE_EXTERNAL_OES)) {
// this is in fact an external texture, this becomes a no-op.
return;
}
// TODO: maybe assert that the CompressedPixelDataType is the same than the internalFormat
GLsizei imageSize = GLsizei(p.imageSize);
// TODO: maybe assert the size is right (b/c we can compute it ourselves)
switch (t->target) {
case SamplerType::SAMPLER_EXTERNAL:
// if we get there, it's because the user is trying to use an external texture
// but it's not supported, so instead, we behave like a texture2d.
// fallthrough...
case SamplerType::SAMPLER_2D:
// NOTE: GL_TEXTURE_2D_MULTISAMPLE is not allowed
bindTexture(OpenGLContext::MAX_TEXTURE_UNIT_COUNT - 1, t);
gl.activeTexture(OpenGLContext::MAX_TEXTURE_UNIT_COUNT - 1);
assert(t->gl.target == GL_TEXTURE_2D);
glCompressedTexSubImage2D(t->gl.target, GLint(level),
GLint(xoffset), GLint(yoffset),
width, height, t->gl.internalFormat, imageSize, p.buffer);
break;
case SamplerType::SAMPLER_2D_ARRAY:
assert(t->gl.target == GL_TEXTURE_2D_ARRAY);
glCompressedTexSubImage3D(t->gl.target, GLint(level),
GLint(xoffset), GLint(yoffset), GLint(zoffset),
width, height, depth, t->gl.internalFormat, imageSize, p.buffer);
break;
case SamplerType::SAMPLER_CUBEMAP: {
assert(faceOffsets);
assert(t->gl.target == GL_TEXTURE_CUBE_MAP);
bindTexture(OpenGLContext::MAX_TEXTURE_UNIT_COUNT - 1, t);
gl.activeTexture(OpenGLContext::MAX_TEXTURE_UNIT_COUNT - 1);
FaceOffsets const& offsets = *faceOffsets;
#pragma nounroll
for (size_t face = 0; face < 6; face++) {
GLenum target = getCubemapTarget(TextureCubemapFace(face));
glCompressedTexSubImage2D(target, GLint(level), 0, 0,
t->width >> level, t->height >> level, t->gl.internalFormat,
imageSize, static_cast<uint8_t const*>(p.buffer) + offsets[face]);
}
break;
}
}
// update the base/max LOD so we don't access undefined LOD. this allows the app to
// specify levels as they become available.
if (uint8_t(level) < t->gl.baseLevel) {
t->gl.baseLevel = uint8_t(level);
glTexParameteri(t->gl.target, GL_TEXTURE_BASE_LEVEL, t->gl.baseLevel);
}
if (uint8_t(level) > t->gl.maxLevel) {
t->gl.maxLevel = uint8_t(level);
glTexParameteri(t->gl.target, GL_TEXTURE_MAX_LEVEL, t->gl.maxLevel);
}
scheduleDestroy(std::move(p));
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::setupExternalImage(void* image) {
mPlatform.retainExternalImage(image);
}
void OpenGLDriver::cancelExternalImage(void* image) {
mPlatform.releaseExternalImage(image);
}
void OpenGLDriver::setExternalImage(Handle<HwTexture> th, void* image) {
mPlatform.setExternalImage(image, handle_cast<GLTexture*>(th));
setExternalTexture(handle_cast<GLTexture*>(th), image);
}
void OpenGLDriver::setExternalImagePlane(Handle<HwTexture> th, void* image, size_t plane) {
}
void OpenGLDriver::setExternalTexture(GLTexture* t, void* image) {
auto& gl = mContext;
// TODO: move this logic to PlatformEGL.
if (gl.ext.OES_EGL_image_external_essl3) {
DEBUG_MARKER()
assert(t->target == SamplerType::SAMPLER_EXTERNAL);
assert(t->gl.target == GL_TEXTURE_EXTERNAL_OES);
bindTexture(OpenGLContext::MAX_TEXTURE_UNIT_COUNT - 1, t);
gl.activeTexture(OpenGLContext::MAX_TEXTURE_UNIT_COUNT - 1);
#ifdef GL_OES_EGL_image
glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, static_cast<GLeglImageOES>(image));
#endif
}
}
void OpenGLDriver::setExternalStream(Handle<HwTexture> th, Handle<HwStream> sh) {
auto& gl = mContext;
if (gl.ext.OES_EGL_image_external_essl3) {
DEBUG_MARKER()
GLTexture* t = handle_cast<GLTexture*>(th);
if (UTILS_LIKELY(sh)) {
GLStream* s = handle_cast<GLStream*>(sh);
if (UTILS_LIKELY(!t->hwStream)) {
// we're not attached already
attachStream(t, s);
} else {
if (s->stream != t->hwStream->stream) {
// attaching to a different stream, detach the old one first
replaceStream(t, s);
}
}
} else if (t->hwStream) {
// do nothing if we're not attached already
detachStream(t);
}
}
}
UTILS_NOINLINE
void OpenGLDriver::attachStream(GLTexture* t, GLStream* hwStream) noexcept {
auto& gl = mContext;
mExternalStreams.push_back(t);
switch (hwStream->streamType) {
case StreamType::NATIVE:
mPlatform.attach(hwStream->stream, t->gl.id);
break;
case StreamType::TEXTURE_ID:
assert(t->target == SamplerType::SAMPLER_EXTERNAL);
// The texture doesn't need a texture name anymore, get rid of it
gl.unbindTexture(t->gl.target, t->gl.id);
glDeleteTextures(1, &t->gl.id);
t->gl.id = hwStream->user_thread.read[hwStream->user_thread.cur];
break;
case StreamType::ACQUIRED:
break;
}
t->hwStream = hwStream;
}
UTILS_NOINLINE
void OpenGLDriver::detachStream(GLTexture* t) noexcept {
auto& gl = mContext;
auto& streams = mExternalStreams;
auto pos = std::find(streams.begin(), streams.end(), t);
if (pos != streams.end()) {
streams.erase(pos);
}
GLStream* s = static_cast<GLStream*>(t->hwStream);
switch (s->streamType) {
case StreamType::NATIVE:
mPlatform.detach(t->hwStream->stream);
// ^ this deletes the texture id
break;
case StreamType::TEXTURE_ID:
break;
case StreamType::ACQUIRED:
gl.unbindTexture(t->gl.target, t->gl.id);
glDeleteTextures(1, &t->gl.id);
break;
}
glGenTextures(1, &t->gl.id);
t->hwStream = nullptr;
}
UTILS_NOINLINE
void OpenGLDriver::replaceStream(GLTexture* texture, GLStream* newStream) noexcept {
assert(newStream && "Do not use replaceStream to detach a stream.");
// This could be implemented via detachStream + attachStream but inlining allows
// a few small optimizations, like not touching the mExternalStreams list.
GLStream* oldStream = static_cast<GLStream*>(texture->hwStream);
switch (oldStream->streamType) {
case StreamType::NATIVE:
mPlatform.detach(texture->hwStream->stream);
// ^ this deletes the texture id
break;
case StreamType::TEXTURE_ID:
case StreamType::ACQUIRED:
break;
}
switch (newStream->streamType) {
case StreamType::NATIVE:
glGenTextures(1, &texture->gl.id);
mPlatform.attach(newStream->stream, texture->gl.id);
break;
case StreamType::TEXTURE_ID:
assert(texture->target == SamplerType::SAMPLER_EXTERNAL);
texture->gl.id = newStream->user_thread.read[newStream->user_thread.cur];
break;
case StreamType::ACQUIRED:
// Just re-use the old texture id.
break;
}
texture->hwStream = newStream;
}
void OpenGLDriver::beginTimerQuery(Handle<HwTimerQuery> tqh) {
GLTimerQuery* tq = handle_cast<GLTimerQuery*>(tqh);
// reset the state of the result availability
tq->elapsed.store(0, std::memory_order_relaxed);
mTimerQueryImpl->beginTimeElapsedQuery(tq);
}
void OpenGLDriver::endTimerQuery(Handle<HwTimerQuery> tqh) {
GLTimerQuery* tq = handle_cast<GLTimerQuery*>(tqh);
mTimerQueryImpl->endTimeElapsedQuery(tq);
runEveryNowAndThen([this, tq]() -> bool {
if (!mTimerQueryImpl->queryResultAvailable(tq)) {
// we need to try this one again later
return false;
}
tq->elapsed.store(mTimerQueryImpl->queryResult(tq), std::memory_order_relaxed);
return true;
});
}
bool OpenGLDriver::getTimerQueryValue(Handle<HwTimerQuery> tqh, uint64_t* elapsedTime) {
GLTimerQuery* tq = handle_cast<GLTimerQuery*>(tqh);
uint64_t d = tq->elapsed.load(std::memory_order_relaxed);
if (!d) {
return false;
}
if (elapsedTime) {
*elapsedTime = d;
}
return true;
}
SyncStatus OpenGLDriver::getSyncStatus(Handle<HwSync> sh) {
GLSync* s = handle_cast<GLSync*>(sh);
if (!s->result) {
return SyncStatus::NOT_SIGNALED;
}
auto status = s->result->status.load(std::memory_order_relaxed);
switch (status) {
case GL_CONDITION_SATISFIED:
case GL_ALREADY_SIGNALED:
return SyncStatus::SIGNALED;
case GL_TIMEOUT_EXPIRED:
return SyncStatus::NOT_SIGNALED;
case GL_WAIT_FAILED:
default:
return SyncStatus::ERROR;
}
}
void OpenGLDriver::beginRenderPass(Handle<HwRenderTarget> rth,
const RenderPassParams& params) {
DEBUG_MARKER()
auto& gl = mContext;
mRenderPassTarget = rth;
mRenderPassParams = params;
GLRenderTarget* rt = handle_cast<GLRenderTarget*>(rth);
const TargetBufferFlags clearFlags = params.flags.clear & rt->targets;
TargetBufferFlags discardFlags = params.flags.discardStart & rt->targets;
gl.bindFramebuffer(GL_FRAMEBUFFER, rt->gl.fbo);
// glInvalidateFramebuffer appeared on GLES 3.0 and GL4.3, for simplicity we just
// ignore it on GL (rather than having to do a runtime check).
if (GLES30_HEADERS) {
if (!gl.bugs.disable_invalidate_framebuffer) {
std::array<GLenum, 6> attachments; // NOLINT
GLsizei attachmentCount = getAttachments(attachments, rt, discardFlags);
if (attachmentCount) {
glInvalidateFramebuffer(GL_FRAMEBUFFER, attachmentCount, attachments.data());
}
CHECK_GL_ERROR(utils::slog.e)
}
}
if (rt->gl.fbo_read) {
// we have a multi-sample RenderTarget with non multi-sample attachments (i.e. this is the
// EXT_multisampled_render_to_texture emulation).
// We need to perform a "backward" resolve, i.e. load the resolved texture into the tile,
// everything must appear as though the multi-sample buffer was lost.
if (ALLOW_REVERSE_MULTISAMPLE_RESOLVE) {
// We only copy the non msaa buffers that were not discarded or cleared.
const TargetBufferFlags discarded = discardFlags | clearFlags;
resolvePass(ResolveAction::LOAD, rt, discarded);
} else {
// However, for now filament specifies that a non multi-sample attachment to a
// multi-sample RenderTarget is always discarded. We do this because implementing
// the load on Metal is not trivial and it's not a feature we rely on at this time.
discardFlags |= rt->gl.resolve;
}
}
if (any(clearFlags)) {
gl.disable(GL_SCISSOR_TEST);
clearWithRasterPipe(clearFlags,
params.clearColor, params.clearDepth, params.clearStencil);
}
// we need to reset those after we call clearWithRasterPipe()
mRenderPassColorWrite = any(clearFlags & TargetBufferFlags::COLOR_ALL);
mRenderPassDepthWrite = any(clearFlags & TargetBufferFlags::DEPTH);
gl.viewport(params.viewport.left, params.viewport.bottom,
params.viewport.width, params.viewport.height);
#ifndef NDEBUG
// clear the discarded (but not the cleared ones) buffers in debug builds
mContext.bindFramebuffer(GL_FRAMEBUFFER, rt->gl.fbo);
mContext.disable(GL_SCISSOR_TEST);
clearWithRasterPipe(discardFlags & ~clearFlags,
{ 1, 0, 0, 1 }, 1.0, 0);
#endif
}
void OpenGLDriver::endRenderPass(int) {
DEBUG_MARKER()
auto& gl = mContext;
assert(mRenderPassTarget); // endRenderPass() called without beginRenderPass()?
GLRenderTarget const* const rt = handle_cast<GLRenderTarget*>(mRenderPassTarget);
TargetBufferFlags discardFlags = mRenderPassParams.flags.discardEnd & rt->targets;
if (rt->gl.fbo_read) {
resolvePass(ResolveAction::STORE, rt, discardFlags);
}
if (!mRenderPassColorWrite) {
discardFlags &= ~TargetBufferFlags::COLOR_ALL;
}
if (!mRenderPassDepthWrite) {
discardFlags &= ~TargetBufferFlags::DEPTH;
}
// glInvalidateFramebuffer appeared on GLES 3.0 and GL4.3, for simplicity we just
// ignore it on GL (rather than having to do a runtime check).
if (GLES30_HEADERS) {
if (!gl.bugs.disable_invalidate_framebuffer) {
// we wouldn't have to bind the framebuffer if we had glInvalidateNamedFramebuffer()
gl.bindFramebuffer(GL_FRAMEBUFFER, rt->gl.fbo);
std::array<GLenum, 6> attachments; // NOLINT
GLsizei attachmentCount = getAttachments(attachments, rt, discardFlags);
if (attachmentCount) {
glInvalidateFramebuffer(GL_FRAMEBUFFER, attachmentCount, attachments.data());
}
CHECK_GL_ERROR(utils::slog.e)
}
}
#ifndef NDEBUG
// clear the discarded buffers in debug builds
mContext.bindFramebuffer(GL_FRAMEBUFFER, rt->gl.fbo);
mContext.disable(GL_SCISSOR_TEST);
clearWithRasterPipe(discardFlags,
{ 0, 1, 0, 1 }, 1.0, 0);
#endif
mRenderPassTarget.clear();
}
void OpenGLDriver::resolvePass(ResolveAction action, GLRenderTarget const* rt,
backend::TargetBufferFlags discardFlags) noexcept {
assert(rt->gl.fbo_read);
auto& gl = mContext;
const TargetBufferFlags resolve = rt->gl.resolve & ~discardFlags;
GLbitfield mask = getAttachmentBitfield(resolve);
if (UTILS_UNLIKELY(mask)) {
GLint read = rt->gl.fbo_read;
GLint draw = rt->gl.fbo;
if (action == ResolveAction::STORE) {
std::swap(read, draw);
}
gl.bindFramebuffer(GL_READ_FRAMEBUFFER, read);
gl.bindFramebuffer(GL_DRAW_FRAMEBUFFER, draw);
gl.disable(GL_SCISSOR_TEST);
glBlitFramebuffer(0, 0, rt->width, rt->height,
0, 0, rt->width, rt->height, mask, GL_NEAREST);
CHECK_GL_ERROR(utils::slog.e)
}
}
GLsizei OpenGLDriver::getAttachments(std::array<GLenum, 6>& attachments,
GLRenderTarget const* rt, TargetBufferFlags buffers) noexcept {
assert(buffers <= rt->targets);
GLsizei attachmentCount = 0;
// the default framebuffer uses different constants!!!
const bool defaultFramebuffer = (rt->gl.fbo == 0);
if (any(buffers & TargetBufferFlags::COLOR0)) {
attachments[attachmentCount++] = defaultFramebuffer ? GL_COLOR : GL_COLOR_ATTACHMENT0;
}
if (any(buffers & TargetBufferFlags::COLOR1)) {
assert(!defaultFramebuffer);
attachments[attachmentCount++] = GL_COLOR_ATTACHMENT1;
}
if (any(buffers & TargetBufferFlags::COLOR2)) {
assert(!defaultFramebuffer);
attachments[attachmentCount++] = GL_COLOR_ATTACHMENT2;
}
if (any(buffers & TargetBufferFlags::COLOR3)) {
assert(!defaultFramebuffer);
attachments[attachmentCount++] = GL_COLOR_ATTACHMENT3;
}
if (any(buffers & TargetBufferFlags::DEPTH)) {
attachments[attachmentCount++] = defaultFramebuffer ? GL_DEPTH : GL_DEPTH_ATTACHMENT;
}
if (any(buffers & TargetBufferFlags::STENCIL)) {
attachments[attachmentCount++] = defaultFramebuffer ? GL_STENCIL : GL_STENCIL_ATTACHMENT;
}
return attachmentCount;
}
void OpenGLDriver::setRenderPrimitiveBuffer(Handle<HwRenderPrimitive> rph,
Handle<HwVertexBuffer> vbh, Handle<HwIndexBuffer> ibh,
uint32_t enabledAttributes) {
DEBUG_MARKER()
auto& gl = mContext;
if (rph) {
GLRenderPrimitive* const rp = handle_cast<GLRenderPrimitive*>(rph);
GLVertexBuffer const* const eb = handle_cast<const GLVertexBuffer*>(vbh);
GLIndexBuffer const* const ib = handle_cast<const GLIndexBuffer*>(ibh);
assert(ib->elementSize == 2 || ib->elementSize == 4);
gl.bindVertexArray(&rp->gl);
CHECK_GL_ERROR(utils::slog.e)
rp->gl.indicesType = ib->elementSize == 4 ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT;
rp->maxVertexCount = eb->vertexCount;
for (size_t i = 0, n = eb->attributes.size(); i < n; i++) {
if (enabledAttributes & (1U << i)) {
uint8_t bi = eb->attributes[i].buffer;
assert(bi != 0xFF);
gl.bindBuffer(GL_ARRAY_BUFFER, eb->gl.buffers[bi]);
if (UTILS_UNLIKELY(eb->attributes[i].flags & Attribute::FLAG_INTEGER_TARGET)) {
glVertexAttribIPointer(GLuint(i),
getComponentCount(eb->attributes[i].type),
getComponentType(eb->attributes[i].type),
eb->attributes[i].stride,
(void*) uintptr_t(eb->attributes[i].offset));
} else {
glVertexAttribPointer(GLuint(i),
getComponentCount(eb->attributes[i].type),
getComponentType(eb->attributes[i].type),
getNormalization(eb->attributes[i].flags & Attribute::FLAG_NORMALIZED),
eb->attributes[i].stride,
(void*) uintptr_t(eb->attributes[i].offset));
}
gl.enableVertexAttribArray(GLuint(i));
} else {
// In some OpenGL implementations, we must supply a properly-typed placeholder for
// every integer input that is declared in the vertex shader.
if (UTILS_UNLIKELY(eb->attributes[i].flags & Attribute::FLAG_INTEGER_TARGET)) {
glVertexAttribI4ui(GLuint(i), 0, 0, 0, 0);
} else {
glVertexAttrib4f(GLuint(i), 0, 0, 0, 0);
}
gl.disableVertexAttribArray(GLuint(i));
}
}
// this records the index buffer into the currently bound VAO
gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib->gl.buffer);
CHECK_GL_ERROR(utils::slog.e)
}
}
void OpenGLDriver::setRenderPrimitiveRange(Handle<HwRenderPrimitive> rph,
PrimitiveType pt, uint32_t offset,
uint32_t minIndex, uint32_t maxIndex, uint32_t count) {
DEBUG_MARKER()
GLRenderPrimitive* const rp = handle_cast<GLRenderPrimitive*>(rph);
rp->type = pt;
rp->offset = offset * ((rp->gl.indicesType == GL_UNSIGNED_INT) ? 4 : 2);
rp->count = count;
rp->minIndex = minIndex;
rp->maxIndex = maxIndex > minIndex ? maxIndex : rp->maxVertexCount - 1; // sanitize max index
}
// Sets up a scissor rectangle that automatically gets clipped against the viewport.
void OpenGLDriver::setViewportScissor(Viewport const& viewportScissor) noexcept {
DEBUG_MARKER()
auto& gl = mContext;
// In OpenGL, all four scissor parameters are actually signed, so clamp to MAX_INT32.
const int32_t maxval = std::numeric_limits<int32_t>::max();
int32_t left = std::min(viewportScissor.left, maxval);
int32_t bottom = std::min(viewportScissor.bottom, maxval);
uint32_t width = std::min(viewportScissor.width, uint32_t(maxval));
uint32_t height = std::min(viewportScissor.height, uint32_t(maxval));
// Compute the intersection of the requested scissor rectangle with the current viewport.
// Note that the viewport rectangle isn't necessarily equal to the bounds of the current
// Filament View (e.g., when post-processing is enabled).
OpenGLContext::vec4gli scissor;
OpenGLContext::vec4gli viewport = gl.getViewport();
scissor.x = std::max((int32_t)left, viewport[0]);
scissor.y = std::max((int32_t)bottom, viewport[1]);
int32_t right = std::min((int32_t)left + (int32_t)width, viewport[0] + viewport[2]);
int32_t top = std::min((int32_t)bottom + (int32_t)height, viewport[1] + viewport[3]);
// Compute width / height of the intersected region. If there's no intersection, pass zeroes
// rather than negative values to satisfy OpenGL requirements.
scissor.z = std::max(0, right - scissor.x);
scissor.w = std::max(0, top - scissor.y);
gl.setScissor(scissor.x, scissor.y, scissor.z, scissor.w);
gl.enable(GL_SCISSOR_TEST);
}
// Binds the external image stashed in the associated stream.
//
// updateStreamAcquired() and setAcquiredImage() are both called from on the application's thread
// and therefore do not require synchronization. The former is always called immediately before
// beginFrame, the latter is called by the user from anywhere outside beginFrame / endFrame.
void OpenGLDriver::updateStreamAcquired(GLTexture* gltexture, DriverApi* driver) noexcept {
SYSTRACE_CALL();
GLStream* glstream = static_cast<GLStream*>(gltexture->hwStream);
assert(glstream);
assert(glstream->streamType == StreamType::ACQUIRED);
// If there's no pending image, do nothing. Note that GL_OES_EGL_image does not let you pass
// NULL to glEGLImageTargetTexture2DOES, and there is no concept of "detaching" an EGLimage from
// a texture.
if (glstream->user_thread.pending.image == nullptr) {
return;
}
AcquiredImage previousImage = glstream->user_thread.acquired;
glstream->user_thread.acquired = glstream->user_thread.pending;
glstream->user_thread.pending = {0};
// Bind the stashed EGLImage to its corresponding GL texture as soon as we start making the GL
// calls for the upcoming frame.
void* image = glstream->user_thread.acquired.image;
driver->queueCommand([this, gltexture, image, previousImage]() {
setExternalTexture(gltexture, image);
if (previousImage.image) {
scheduleRelease(AcquiredImage(previousImage));
}
});
}
#define DEBUG_NO_EXTERNAL_STREAM_COPY false
void OpenGLDriver::updateStreamTexId(GLTexture* t, DriverApi* driver) noexcept {
SYSTRACE_CALL();
auto& gl = mContext;
GLStream* s = static_cast<GLStream*>(t->hwStream);
assert(s);
assert(s->streamType == StreamType::TEXTURE_ID);
// round-robin to the next texture name
if (UTILS_UNLIKELY(DEBUG_NO_EXTERNAL_STREAM_COPY ||
gl.bugs.disable_shared_context_draws || !mOpenGLBlitter)) {
driver->queueCommand([this, t, s]() {
// the stream may have been destroyed since we enqueued the command
// also make sure that this texture is still associated with the same stream
auto& streams = mExternalStreams;
if (UTILS_LIKELY(std::find(streams.begin(), streams.end(), t) != streams.end()) &&
(t->hwStream == s)) {
t->gl.id = s->gl.externalTextureId;
}
});
} else {
s->user_thread.cur = uint8_t(
(s->user_thread.cur + 1) % GLStream::ROUND_ROBIN_TEXTURE_COUNT);
GLuint writeTexture = s->user_thread.write[s->user_thread.cur];
GLuint readTexture = s->user_thread.read[s->user_thread.cur];
// Make sure we're using the proper size
GLStream::Info& info = s->user_thread.infos[s->user_thread.cur];
if (UTILS_UNLIKELY(info.width != s->width || info.height != s->height)) {
// nothing guarantees that this buffer is free (i.e. has been consumed by the
// GL thread), so we could potentially cause a glitch by reallocating the
// texture here. This should be very rare though.
// This could be fixed by always using a new temporary texture here, and
// replacing it in the queueCommand() below. imho, not worth it.
info.width = s->width;
info.height = s->height;
Platform::ExternalTexture* ets = s->user_thread.infos[s->user_thread.cur].ets;
mPlatform.reallocateExternalStorage(ets, info.width, info.height, TextureFormat::RGB8);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, writeTexture);
glBindTexture(GL_TEXTURE_EXTERNAL_OES, readTexture);
#ifdef GL_OES_EGL_image
glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, (GLeglImageOES)ets->image);
glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, (GLeglImageOES)ets->image);
#endif
}
// copy the texture...
#ifndef NDEBUG
if (t->gl.fence) {
// we're about to overwrite a buffer that hasn't been consumed
slog.d << "OpenGLDriver::updateStream(): about to overwrite buffer " <<
int(s->user_thread.cur) << " of Texture at " << t << " of Stream at " << s
<< io::endl;
}
#endif
mOpenGLBlitter->blit(s->gl.externalTextureId, writeTexture, s->width, s->height);
// We need a fence to guarantee that this copy has happened when we need the texture
// in OpenGLProgram::updateSamplers(), i.e. when we bind textures just before use.
GLsync fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
// Per https://www.khronos.org/opengl/wiki/Sync_Object, flush to make sure that the
// sync object is in the driver's command queue.
glFlush();
// Update the stream timestamp. It's not clear to me that this is correct; which
// timestamp do we really want? Here we use "now" because we have nothing else we
// can use.
s->user_thread.timestamp = std::chrono::steady_clock::now().time_since_epoch().count();
driver->queueCommand([this, t, s, fence, readTexture, writeTexture]() {
// the stream may have been destroyed since we enqueued the command
// also make sure that this texture is still associated with the same stream
auto& streams = mExternalStreams;
if (UTILS_LIKELY(std::find(streams.begin(), streams.end(), t) != streams.end()) &&
(t->hwStream == s)) {
if (UTILS_UNLIKELY(t->gl.fence)) {
// if the texture still has a fence set, destroy it now, so it's not leaked.
glDeleteSync(t->gl.fence);
}
t->gl.id = readTexture;
t->gl.fence = fence;
s->gl.externalTexture2DId = writeTexture;
} else {
glDeleteSync(fence);
}
});
}
}
void OpenGLDriver::readStreamPixels(Handle<HwStream> sh,
uint32_t x, uint32_t y, uint32_t width, uint32_t height,
PixelBufferDescriptor&& p) {
DEBUG_MARKER()
auto& gl = mContext;
GLStream* s = handle_cast<GLStream*>(sh);
if (UTILS_UNLIKELY(s->streamType == StreamType::ACQUIRED)) {
PANIC_LOG("readStreamPixels with ACQUIRED streams is not yet implemented.");
return;
}
if (UTILS_LIKELY(s->streamType == StreamType::TEXTURE_ID)) {
GLuint tid = s->gl.externalTexture2DId;
if (tid == 0) {
return;
}
GLenum glFormat = getFormat(p.format);
GLenum glType = getType(p.type);
gl.pixelStore(GL_PACK_ROW_LENGTH, p.stride);
gl.pixelStore(GL_PACK_ALIGNMENT, p.alignment);
gl.pixelStore(GL_PACK_SKIP_PIXELS, p.left);
gl.pixelStore(GL_PACK_SKIP_ROWS, p.top);
if (s->gl.fbo == 0) {
glGenFramebuffers(1, &s->gl.fbo);
}
gl.bindFramebuffer(GL_FRAMEBUFFER, s->gl.fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tid, 0);
CHECK_GL_ERROR(utils::slog.e)
/*
* It looks like glReadPixels() behaves differently, or even wrongly,
* when the FBO is backed by an EXTERNAL texture...
*
*
* External texture FBO User buffer
*
* O---+----------------+
* | | | .stride .alignment
* | | | ----------------------->-->
* | | y | O----------------------+--+ low adresses
* | | | | | | |
* | | w | | | .bottom | |
* | V <---------> | | V | |
* | +---------+ | | +---------+ | |
* | | ^ | | ======> | | | | |
* | x | h| | | |.left| | | |
* +------>| v | | +---->| | | |
* | +.........+ | | +.........+ | |
* | | | | |
* | | +----------------------+--+ high adresses
* +--------------------+
*
* Origin is at the The image is NOT y-reversed
* top-left corner and bottom is counted from
* the top! "bottom" is in fact treated
* as "top".
*/
// The filament API provides yoffset as the "bottom" offset, therefore it needs to
// be corrected to match glReadPixels()'s behavior.
y = (s->height - height) - y;
// TODO: we could use a PBO to make this asynchronous
glReadPixels(GLint(x), GLint(y), GLint(width), GLint(height), glFormat, glType, p.buffer);
CHECK_GL_ERROR(utils::slog.e)
gl.bindFramebuffer(GL_FRAMEBUFFER, 0);
scheduleDestroy(std::move(p));
}
}
// ------------------------------------------------------------------------------------------------
// Setting rendering state
// ------------------------------------------------------------------------------------------------
void OpenGLDriver::bindUniformBuffer(size_t index, Handle<HwUniformBuffer> ubh) {
DEBUG_MARKER()
auto& gl = mContext;
GLUniformBuffer* ub = handle_cast<GLUniformBuffer *>(ubh);
assert(ub->gl.ubo.base == 0);
gl.bindBufferRange(GL_UNIFORM_BUFFER, GLuint(index), ub->gl.ubo.id, 0, ub->gl.ubo.capacity);
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::bindUniformBufferRange(size_t index, Handle<HwUniformBuffer> ubh,
size_t offset, size_t size) {
DEBUG_MARKER()
auto& gl = mContext;
GLUniformBuffer* ub = handle_cast<GLUniformBuffer*>(ubh);
// TODO: Is this assert really needed? Note that size is only populated for STREAM buffers.
assert(size <= ub->gl.ubo.size);
assert(ub->gl.ubo.base + offset + size <= ub->gl.ubo.capacity);
gl.bindBufferRange(GL_UNIFORM_BUFFER, GLuint(index), ub->gl.ubo.id, ub->gl.ubo.base + offset, size);
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::bindSamplers(size_t index, Handle<HwSamplerGroup> sbh) {
DEBUG_MARKER()
GLSamplerGroup* sb = handle_cast<GLSamplerGroup *>(sbh);
assert(index < Program::SAMPLER_BINDING_COUNT);
mSamplerBindings[index] = sb;
CHECK_GL_ERROR(utils::slog.e)
}
GLuint OpenGLDriver::getSamplerSlow(SamplerParams params) const noexcept {
assert(mSamplerMap.find(params.u) == mSamplerMap.end());
GLuint s;
glGenSamplers(1, &s);
glSamplerParameteri(s, GL_TEXTURE_MIN_FILTER, getTextureFilter(params.filterMin));
glSamplerParameteri(s, GL_TEXTURE_MAG_FILTER, getTextureFilter(params.filterMag));
glSamplerParameteri(s, GL_TEXTURE_WRAP_S, getWrapMode(params.wrapS));
glSamplerParameteri(s, GL_TEXTURE_WRAP_T, getWrapMode(params.wrapT));
glSamplerParameteri(s, GL_TEXTURE_WRAP_R, getWrapMode(params.wrapR));
glSamplerParameteri(s, GL_TEXTURE_COMPARE_MODE, getTextureCompareMode(params.compareMode));
glSamplerParameteri(s, GL_TEXTURE_COMPARE_FUNC, getTextureCompareFunc(params.compareFunc));
// TODO: Why does this fail with WebGL 2.0? The run-time check should suffice.
#if defined(GL_EXT_texture_filter_anisotropic) && !defined(__EMSCRIPTEN__)
auto& gl = mContext;
if (gl.ext.texture_filter_anisotropic && !gl.bugs.disable_texture_filter_anisotropic) {
GLfloat anisotropy = float(1u << params.anisotropyLog2);
glSamplerParameterf(s, GL_TEXTURE_MAX_ANISOTROPY_EXT, std::min(gl.gets.maxAnisotropy, anisotropy));
}
#endif
CHECK_GL_ERROR(utils::slog.e)
mSamplerMap[params.u] = s;
return s;
}
void OpenGLDriver::insertEventMarker(char const* string, size_t len) {
#ifdef GL_EXT_debug_marker
auto& gl = mContext;
if (gl.ext.EXT_debug_marker) {
glInsertEventMarkerEXT(GLsizei(len ? len : strlen(string)), string);
}
#endif
}
void OpenGLDriver::pushGroupMarker(char const* string, size_t len) {
#ifdef GL_EXT_debug_marker
auto& gl = mContext;
if (gl.ext.EXT_debug_marker) {
glPushGroupMarkerEXT(GLsizei(len ? len : strlen(string)), string);
}
#endif
}
void OpenGLDriver::startCapture(int) {
}
void OpenGLDriver::stopCapture(int) {
}
void OpenGLDriver::popGroupMarker(int) {
#ifdef GL_EXT_debug_marker
auto& gl = mContext;
if (gl.ext.EXT_debug_marker) {
glPopGroupMarkerEXT();
}
#endif
}
// ------------------------------------------------------------------------------------------------
// Read-back ops
// ------------------------------------------------------------------------------------------------
void OpenGLDriver::readPixels(Handle<HwRenderTarget> src,
uint32_t x, uint32_t y, uint32_t width, uint32_t height,
PixelBufferDescriptor&& p) {
DEBUG_MARKER()
auto& gl = mContext;
GLenum glFormat = getFormat(p.format);
GLenum glType = getType(p.type);
gl.pixelStore(GL_PACK_ROW_LENGTH, p.stride);
gl.pixelStore(GL_PACK_ALIGNMENT, p.alignment);
gl.pixelStore(GL_PACK_SKIP_PIXELS, p.left);
gl.pixelStore(GL_PACK_SKIP_ROWS, p.top);
/*
* glReadPixel() operation...
*
* Framebuffer as seen on User buffer
* screen
* +--------------------+
* | | stride alignment
* | | ----------------------->-->
* | | +----------------------+--+ low adresses
* | | | | | |
* | w | | | bottom | |
* | <---------> | | V | |
* | +---------+ | | +.........+ | |
* | | ^ | | =====> | | | | |
* | x | h| | | |left | | | |
* +------>| v | | +---->| | | |
* | +.........+ | | +---------+ | |
* | ^ | | | |
* | y | | +----------------------+--+ high adresses
* +------------+-------+
* Image is "flipped" vertically
* "bottom" is from the "top" (low addresses)
* of the buffer.
*/
GLRenderTarget const* s = handle_cast<GLRenderTarget const*>(src);
gl.bindFramebuffer(GL_READ_FRAMEBUFFER, s->gl.fbo);
GLuint pbo;
glGenBuffers(1, &pbo);
gl.bindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
glBufferData(GL_PIXEL_PACK_BUFFER, p.size, nullptr, GL_STATIC_DRAW);
glReadPixels(GLint(x), GLint(y), GLint(width), GLint(height), glFormat, glType, nullptr);
gl.bindBuffer(GL_PIXEL_PACK_BUFFER, 0);
// we're forced to make a copy on the heap because otherwise it deletes std::function<> copy
// constructor.
auto* pUserBuffer = new PixelBufferDescriptor(std::move(p));
whenGpuCommandsComplete([this, width, height, pbo, pUserBuffer]() mutable {
PixelBufferDescriptor& p = *pUserBuffer;
auto& gl = mContext;
gl.bindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
void* vaddr = glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, p.size, GL_MAP_READ_BIT);
if (vaddr) {
// now we need to flip the buffer vertically to match our API
size_t stride = p.stride ? p.stride : width;
size_t bpp = PixelBufferDescriptor::computeDataSize(
p.format, p.type, 1, 1, 1);
size_t bpr = PixelBufferDescriptor::computeDataSize(
p.format, p.type, stride, 1, p.alignment);
char const* head = (char const*)vaddr + p.left * bpp + bpr * p.top;
char* tail = (char*)p.buffer + p.left * bpp + bpr * (p.top + height - 1);
for (size_t i = 0; i < height; ++i) {
memcpy(tail, head, bpp * width);
head += bpr;
tail -= bpr;
}
glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
}
gl.bindBuffer(GL_PIXEL_PACK_BUFFER, 0);
glDeleteBuffers(1, &pbo);
scheduleDestroy(std::move(p));
delete pUserBuffer;
CHECK_GL_ERROR(utils::slog.e)
});
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::whenGpuCommandsComplete(std::function<void()> fn) noexcept {
GLsync sync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
mGpuCommandCompleteOps.emplace_back(sync, std::move(fn));
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::runEveryNowAndThen(std::function<bool()> fn) noexcept {
mEveryNowAndThenOps.push_back(std::move(fn));
}
void OpenGLDriver::executeGpuCommandsCompleteOps() noexcept {
auto& v = mGpuCommandCompleteOps;
auto it = v.begin();
while (it != v.end()) {
GLenum status = glClientWaitSync(it->first, 0, 0);
if (status == GL_ALREADY_SIGNALED || status == GL_CONDITION_SATISFIED) {
it->second();
glDeleteSync(it->first);
it = v.erase(it);
} else if (UTILS_UNLIKELY(status == GL_WAIT_FAILED)) {
// This should never happen, but is very problematic if it does, as we might leak
// some data depending on what the callback does. However, we clean-up our own state.
glDeleteSync(it->first);
it = v.erase(it);
} else {
++it;
}
}
}
void OpenGLDriver::executeEveryNowAndThenOps() noexcept {
auto& v = mEveryNowAndThenOps;
auto it = v.begin();
while (it != v.end()) {
if ((*it)()) {
it = v.erase(it);
} else {
++it;
}
}
}
// ------------------------------------------------------------------------------------------------
// Rendering ops
// ------------------------------------------------------------------------------------------------
void OpenGLDriver::tick(int) {
executeGpuCommandsCompleteOps();
executeEveryNowAndThenOps();
}
void OpenGLDriver::beginFrame(int64_t monotonic_clock_ns, uint32_t frameId,
backend::FrameFinishedCallback, void*) {
auto& gl = mContext;
insertEventMarker("beginFrame");
if (UTILS_UNLIKELY(!mExternalStreams.empty())) {
OpenGLPlatform& platform = mPlatform;
for (GLTexture const* t : mExternalStreams) {
assert(t && t->hwStream);
if (t->hwStream->streamType == StreamType::NATIVE) {
assert(t->hwStream->stream);
platform.updateTexImage(t->hwStream->stream,
&static_cast<GLStream*>(t->hwStream)->user_thread.timestamp);
// NOTE: We assume that updateTexImage() binds the texture on our behalf
gl.updateTexImage(GL_TEXTURE_EXTERNAL_OES, t->gl.id);
}
}
}
}
void OpenGLDriver::setPresentationTime(int64_t monotonic_clock_ns) {
mPlatform.setPresentationTime(monotonic_clock_ns);
}
void OpenGLDriver::endFrame(uint32_t frameId) {
//SYSTRACE_NAME("glFinish");
//glFinish();
insertEventMarker("endFrame");
}
void OpenGLDriver::flush(int) {
DEBUG_MARKER()
auto& gl = mContext;
if (!gl.bugs.disable_glFlush) {
glFlush();
}
mTimerQueryImpl->flush();
}
void OpenGLDriver::finish(int) {
DEBUG_MARKER()
glFinish();
mTimerQueryImpl->flush();
executeGpuCommandsCompleteOps();
executeEveryNowAndThenOps();
// Note: since we executed a glFinish(), all pending tasks should be done
assert(mGpuCommandCompleteOps.empty());
// however, some tasks rely on a separated thread to publish their result (e.g.
// endTimerQuery), so the result could very well not be ready, and the task will
// linger a bit longer, this is only true for mEveryNowAndThenOps tasks.
// The fallout of this is that we can't assert that mEveryNowAndThenOps is empty.
}
UTILS_NOINLINE
void OpenGLDriver::clearWithRasterPipe(TargetBufferFlags clearFlags,
math::float4 const& linearColor, GLfloat depth, GLint stencil) noexcept {
DEBUG_MARKER()
RasterState rs(mRasterState);
if (any(clearFlags & TargetBufferFlags::COLOR_ALL)) {
rs.colorWrite = true;
}
if (any(clearFlags & TargetBufferFlags::DEPTH)) {
rs.depthWrite = true;
}
// stencil state is not part of the RasterState currently
if (any(clearFlags & (TargetBufferFlags::COLOR_ALL | TargetBufferFlags::DEPTH))) {
setRasterState(rs);
}
if (any(clearFlags & TargetBufferFlags::COLOR0)) {
glClearBufferfv(GL_COLOR, 0, linearColor.v);
}
if (any(clearFlags & TargetBufferFlags::COLOR1)) {
glClearBufferfv(GL_COLOR, 1, linearColor.v);
}
if (any(clearFlags & TargetBufferFlags::COLOR2)) {
glClearBufferfv(GL_COLOR, 2, linearColor.v);
}
if (any(clearFlags & TargetBufferFlags::COLOR3)) {
glClearBufferfv(GL_COLOR, 3, linearColor.v);
}
if ((clearFlags & TargetBufferFlags::DEPTH_AND_STENCIL) == TargetBufferFlags::DEPTH_AND_STENCIL) {
glClearBufferfi(GL_DEPTH_STENCIL, 0, depth, stencil);
} else {
if (any(clearFlags & TargetBufferFlags::DEPTH)) {
glClearBufferfv(GL_DEPTH, 0, &depth);
}
if (any(clearFlags & TargetBufferFlags::STENCIL)) {
glClearBufferiv(GL_STENCIL, 0, &stencil);
}
}
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::blit(TargetBufferFlags buffers,
Handle<HwRenderTarget> dst, Viewport dstRect,
Handle<HwRenderTarget> src, Viewport srcRect,
SamplerMagFilter filter) {
DEBUG_MARKER()
auto& gl = mContext;
GLbitfield mask = getAttachmentBitfield(buffers);
if (mask) {
GLenum glFilterMode = (filter == SamplerMagFilter::NEAREST) ? GL_NEAREST : GL_LINEAR;
if (mask & (GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)) {
// GL_INVALID_OPERATION is generated if mask contains any of the GL_DEPTH_BUFFER_BIT or
// GL_STENCIL_BUFFER_BIT and filter is not GL_NEAREST.
glFilterMode = GL_NEAREST;
}
// note: for msaa RenderTargets withh non-msaa attachments, we copy from the msaa sidecar
// buffer -- this should produce the same output that if we copied from the resolved
// texture. EXT_multisampled_render_to_texture seems to allow both behaviours, and this
// is an emulation of that. We cannot use the resolved texture easily because it's not
// actually attached to the this RenderTarget. Another implementation would be to do a
// reverse-resolve, but that wouldn't buy us anything.
GLRenderTarget const* s = handle_cast<GLRenderTarget const*>(src);
GLRenderTarget const* d = handle_cast<GLRenderTarget const*>(dst);
if (!ALLOW_REVERSE_MULTISAMPLE_RESOLVE) {
// With GLES 3.x, GL_INVALID_OPERATION is generated if the value of GL_SAMPLE_BUFFERS
// for the draw buffer is greater than zero. This works with OpenGL, so we want to
// make sure to catch this scenario.
assert(d->gl.samples <= 1);
}
// GL_INVALID_OPERATION is generated if GL_SAMPLE_BUFFERS for the read buffer is greater
// than zero and the formats of draw and read buffers are not identical.
// However, it's not well defined in the spec what "format" means. So it's difficult
// to have an assert here -- especially when dealing with the default framebuffer
// GL_INVALID_OPERATION is generated if GL_SAMPLE_BUFFERS for the read buffer is greater
// than zero and (...) the source and destination rectangles are not defined with the
// same (X0, Y0) and (X1, Y1) bounds.
// Additionally the EXT_multisampled_render_to_texture extension doesn't specify what
// happens when blitting from an "implicit" resolve render target (does it work?), so
// to ere on the safe side, we don't allow it.
if (s->gl.samples > 1) {
assert(!memcmp(&dstRect, &srcRect, sizeof(srcRect)));
}
gl.bindFramebuffer(GL_READ_FRAMEBUFFER, s->gl.fbo);
gl.bindFramebuffer(GL_DRAW_FRAMEBUFFER, d->gl.fbo);
gl.disable(GL_SCISSOR_TEST);
glBlitFramebuffer(
srcRect.left, srcRect.bottom, srcRect.right(), srcRect.top(),
dstRect.left, dstRect.bottom, dstRect.right(), dstRect.top(),
mask, glFilterMode);
CHECK_GL_ERROR(utils::slog.e)
}
}
void OpenGLDriver::updateTextureLodRange(GLTexture* texture, int8_t targetLevel) noexcept {
auto& gl = mContext;
if (texture && any(texture->usage & TextureUsage::SAMPLEABLE)) {
if (targetLevel < texture->gl.baseLevel || targetLevel > texture->gl.maxLevel) {
bindTexture(OpenGLContext::MAX_TEXTURE_UNIT_COUNT - 1, texture);
gl.activeTexture(OpenGLContext::MAX_TEXTURE_UNIT_COUNT - 1);
if (targetLevel < texture->gl.baseLevel) {
texture->gl.baseLevel = targetLevel;
glTexParameteri(texture->gl.target, GL_TEXTURE_BASE_LEVEL, targetLevel);
}
if (targetLevel > texture->gl.maxLevel) {
texture->gl.maxLevel = targetLevel;
glTexParameteri(texture->gl.target, GL_TEXTURE_MAX_LEVEL, targetLevel);
}
}
CHECK_GL_ERROR(utils::slog.e)
}
}
void OpenGLDriver::draw(PipelineState state, Handle<HwRenderPrimitive> rph) {
DEBUG_MARKER()
auto& gl = mContext;
OpenGLProgram* p = handle_cast<OpenGLProgram*>(state.program);
// If the material debugger is enabled, avoid fatal (or cascading) errors and that can occur
// during the draw call when the program is invalid. The shader compile error has already been
// dumped to the console at this point, so it's fine to simply return early.
if (FILAMENT_ENABLE_MATDBG && UTILS_UNLIKELY(!p->isValid())) {
return;
}
useProgram(p);
const GLRenderPrimitive* rp = handle_cast<const GLRenderPrimitive *>(rph);
gl.bindVertexArray(&rp->gl);
setRasterState(state.rasterState);
gl.polygonOffset(state.polygonOffset.slope, state.polygonOffset.constant);
setViewportScissor(state.scissor);
glDrawRangeElements(GLenum(rp->type), rp->minIndex, rp->maxIndex, rp->count,
rp->gl.indicesType, reinterpret_cast<const void*>(rp->offset));
CHECK_GL_ERROR(utils::slog.e)
}
// explicit instantiation of the Dispatcher
template class backend::ConcreteDispatcher<OpenGLDriver>;
} // namespace filament
|
// Copyright Glen Knowles 2018 - 2021.
// Distributed under the Boost Software License, Version 1.0.
//
// fnxfrmlist.cpp - tismet func
//
// Functions that make changes within a single sample list
#include "pch.h"
#pragma hdrstop
using namespace std;
using namespace std::chrono;
using namespace Dim;
using namespace Eval;
/****************************************************************************
*
* IXfrmListBase
*
***/
namespace {
template<typename T>
class IXfrmListBase : public IFuncBase<T> {
bool onFuncApply(IFuncNotify * notify, ResultInfo & info) override;
virtual void onTransform(
double * optr,
const double * ptr,
const double * eptr,
Duration interval
) = 0;
};
} // namespace
//===========================================================================
template<typename T>
bool IXfrmListBase<T>::onFuncApply(IFuncNotify * notify, ResultInfo & info) {
if (info.samples) {
info.name = addFuncName(this->type(), info.name);
auto out = SampleList::alloc(*info.samples);
auto optr = out->samples;
auto ptr = info.samples->samples;
auto eptr = ptr + info.samples->count;
onTransform(optr, ptr, eptr, out->interval);
info.samples = out;
}
notify->onFuncOutput(info);
return true;
}
/****************************************************************************
*
* derivative
*
***/
namespace {
class FuncDerivative : public IXfrmListBase<FuncDerivative> {
IFuncInstance * onFuncBind(vector<const Query::Node *> & args) override;
void onTransform(
double * optr,
const double * ptr,
const double * eptr,
Duration interval
) override;
};
} // namespace
static auto s_derivative = FuncDerivative::Factory("derivative", "Transform")
.arg("query", FuncArg::kPathOrFunc, true);
//===========================================================================
IFuncInstance * FuncDerivative::onFuncBind(
vector<const Query::Node *> & args
) {
m_presamples = 1;
return this;
}
//===========================================================================
void FuncDerivative::onTransform(
double * optr,
const double * ptr,
const double * eptr,
Duration interval
) {
*optr++ = NAN;
for (; ptr != eptr - 1; ++ptr) {
*optr++ = ptr[1] - ptr[0];
}
}
/****************************************************************************
*
* keepLastValue
*
***/
namespace {
class FuncKeepLastValue : public IXfrmListBase<FuncKeepLastValue> {
IFuncInstance * onFuncBind(vector<const Query::Node *> & args) override;
void onTransform(
double * optr,
const double * ptr,
const double * eptr,
Duration interval
) override;
double m_limit;
};
} // namespace
static auto s_keepLastValue =
FuncKeepLastValue::Factory("keepLastValue", "Transform")
.arg("query", FuncArg::kPathOrFunc, true)
.arg("limit", FuncArg::kNum);
//===========================================================================
IFuncInstance * FuncKeepLastValue::onFuncBind(
vector<const Query::Node *> & args
) {
m_limit = args.empty() ? 0 : (int) asNumber(*args[0]);
m_presamples = 1;
return this;
}
//===========================================================================
void FuncKeepLastValue::onTransform(
double * optr,
const double * ptr,
const double * eptr,
Duration interval
) {
auto base = ptr;
int nans = 0;
for (; base != eptr; ++base) {
if (!isnan(*base))
break;
*optr++ = *base;
}
for (ptr = base; ptr != eptr; ++ptr) {
if (isnan(*ptr)) {
if (!nans++) {
for (; base != ptr - 1; ++base)
*optr++ = *base;
}
} else if (nans) {
if (!m_limit || nans <= m_limit) {
auto val = *base;
for (; base != ptr; ++base)
*optr++ = val;
}
nans = 0;
}
}
if (nans && (!m_limit || nans <= m_limit)) {
auto val = *base;
for (; base != ptr; ++base)
*optr++ = val;
} else {
for (; base != ptr; ++base)
*optr++ = *base;
}
}
/****************************************************************************
*
* movingAverage
*
***/
namespace {
class FuncMovingAverage : public IXfrmListBase<FuncMovingAverage> {
IFuncInstance * onFuncBind(vector<const Query::Node *> & args) override;
void onTransform(
double * optr,
const double * ptr,
const double * eptr,
Duration interval
) override;
unsigned m_count{};
};
} // namespace
static auto s_movingAverage =
FuncMovingAverage::Factory("movingAverage", "Calculate")
.arg("query", FuncArg::kPathOrFunc, true)
.arg("windowSize", FuncArg::kNumOrString, true)
.arg("xFilesFactor", FuncArg::kNum, false);
//===========================================================================
IFuncInstance * FuncMovingAverage::onFuncBind(
vector<const Query::Node *> & args
) {
if (auto arg0 = asString(*args[0]); !arg0.empty()) {
if (parse(&m_pretime, arg0))
return this;
m_presamples = strToUint(arg0);
} else {
m_presamples = (unsigned) asNumber(*args[0]);
}
if (m_presamples)
m_presamples -= 1;
return this;
}
//===========================================================================
void FuncMovingAverage::onTransform(
double * optr,
const double * ptr,
const double * eptr,
Duration interval
) {
unsigned count;
if (m_pretime.count()) {
auto pretime = m_pretime - m_pretime % interval;
count = unsigned(pretime / interval) + 1;
} else {
count = m_presamples + 1;
}
auto pre = ptr;
assert(pre + count <= eptr);
double sum = 0;
unsigned nans = 0;
for (unsigned i = 1; i <= count; ++i, ++ptr) {
if (isnan(*ptr)) {
if (++nans == i) {
*optr++ = NAN;
continue;
}
} else {
sum += *ptr;
}
*optr++ = sum / count;
}
for (; ptr != eptr; ++ptr, ++pre) {
if (isnan(*ptr)) {
nans += 1;
} else {
sum += *ptr;
}
if (isnan(*pre)) {
nans -= 1;
} else {
sum -= *pre;
}
*optr++ = (nans == count) ? NAN : sum / count;
}
}
/****************************************************************************
*
* nonNegativeDerivative
*
***/
namespace {
class FuncNonNegativeDerivative
: public IXfrmListBase<FuncNonNegativeDerivative>
{
IFuncInstance * onFuncBind(vector<const Query::Node *> & args) override;
void onTransform(
double * optr,
const double * ptr,
const double * eptr,
Duration interval
) override;
double m_limit;
};
} // namespace
static auto s_nonNegativeDerivative =
FuncNonNegativeDerivative::Factory("nonNegativeDerivative", "Transform")
.arg("query", FuncArg::kPathOrFunc, true)
.arg("maxValue", FuncArg::kNum);
//===========================================================================
IFuncInstance * FuncNonNegativeDerivative::onFuncBind(
vector<const Query::Node *> & args
) {
m_limit = args.empty() ? HUGE_VAL : asNumber(*args[0]);
m_presamples = 1;
return this;
}
//===========================================================================
void FuncNonNegativeDerivative::onTransform(
double * optr,
const double * ptr,
const double * eptr,
Duration interval
) {
*optr++ = NAN;
auto prev = *ptr;
for (ptr += 1; ptr != eptr; ++ptr) {
if (isnan(*ptr) || isnan(prev) || *ptr > m_limit) {
*optr++ = NAN;
prev = *ptr;
} else if (*ptr >= prev) {
*optr++ = *ptr - prev;
prev = *ptr;
} else if (isinf(m_limit)) {
*optr++ = NAN;
prev = *ptr;
} else {
*optr++ = *ptr + (m_limit - prev + 1);
prev = *ptr;
}
}
}
/****************************************************************************
*
* Public API
*
***/
//===========================================================================
void funcXfrmListInitialize()
{}
|
and(1) cr0<1>UD cr0<0,1,0>UD 0xfffffb3fUD { align1 1N switch };
and(1) cr0<1>UD cr0<0,1,0>UD 0xffffff3fUD { align1 1N switch };
and(1) cr0<1>UD cr0<0,1,0>UD 0xfffffb7fUD { align1 1N switch };
and(1) cr0<1>UD cr0<0,1,0>UD 0xffffff7fUD { align1 1N switch };
and(1) cr0<1>UD cr0<0,1,0>UD 0xfffffbbfUD { align1 1N switch };
and(1) cr0<1>UD cr0<0,1,0>UD 0xffffffbfUD { align1 1N switch };
and(1) cr0<1>UD cr0<0,1,0>UD 0xffffffcfUD { align1 1N switch };
and(1) cr0<1>UD cr0<0,1,0>UD 0xfffffbffUD { align1 1N switch };
or(1) cr0<1>UD cr0<0,1,0>UD 0x00000400UD { align1 1N switch };
or(1) cr0<1>UD cr0<0,1,0>UD 0x00000030UD { align1 1N switch };
or(1) cr0<1>UD cr0<0,1,0>UD 0x00000040UD { align1 1N switch };
or(1) cr0<1>UD cr0<0,1,0>UD 0x00000440UD { align1 1N switch };
or(1) cr0<1>UD cr0<0,1,0>UD 0x00000080UD { align1 1N switch };
or(1) cr0<1>UD cr0<0,1,0>UD 0x00000480UD { align1 1N switch };
|
ORG 2000H
MVI A, 82H
OUT 83H
MVI A, 00H
L1: OUT 80H
NOP
NOP
NOP
NOP
NOP
CMA
NOP
NOP
NOP
NOP
NOP
JMP L1
END |
; A157286: a(n) = 36*n^2 - n.
; 35,142,321,572,895,1290,1757,2296,2907,3590,4345,5172,6071,7042,8085,9200,10387,11646,12977,14380,15855,17402,19021,20712,22475,24310,26217,28196,30247,32370,34565,36832,39171,41582,44065,46620,49247,51946,54717,57560,60475,63462,66521,69652,72855,76130,79477,82896,86387,89950,93585,97292,101071,104922,108845,112840,116907,121046,125257,129540,133895,138322,142821,147392,152035,156750,161537,166396,171327,176330,181405,186552,191771,197062,202425,207860,213367,218946,224597,230320,236115,241982,247921,253932,260015,266170,272397,278696,285067,291510,298025,304612,311271,318002,324805,331680,338627,345646,352737,359900,367135,374442,381821,389272,396795,404390,412057,419796,427607,435490,443445,451472,459571,467742,475985,484300,492687,501146,509677,518280,526955,535702,544521,553412,562375,571410,580517,589696,598947,608270,617665,627132,636671,646282,655965,665720,675547,685446,695417,705460,715575,725762,736021,746352,756755,767230,777777,788396,799087,809850,820685,831592,842571,853622,864745,875940,887207,898546,909957,921440,932995,944622,956321,968092,979935,991850,1003837,1015896,1028027,1040230,1052505,1064852,1077271,1089762,1102325,1114960,1127667,1140446,1153297,1166220,1179215,1192282,1205421,1218632,1231915,1245270,1258697,1272196,1285767,1299410,1313125,1326912,1340771,1354702,1368705,1382780,1396927,1411146,1425437,1439800,1454235,1468742,1483321,1497972,1512695,1527490,1542357,1557296,1572307,1587390,1602545,1617772,1633071,1648442,1663885,1679400,1694987,1710646,1726377,1742180,1758055,1774002,1790021,1806112,1822275,1838510,1854817,1871196,1887647,1904170,1920765,1937432,1954171,1970982,1987865,2004820,2021847,2038946,2056117,2073360,2090675,2108062,2125521,2143052,2160655,2178330,2196077,2213896,2231787,2249750
add $0,1
mul $0,36
bin $0,2
mov $1,$0
div $1,18
|
//=================================================================================================
/*!
// \file src/mathtest/svecdvecouter/VCaV5b.cpp
// \brief Source file for the VCaV5b sparse vector/dense vector outer product math test
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. 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 names of the Blaze development group 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedVector.h>
#include <blaze/math/StaticVector.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/svecdvecouter/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'VCaV5b'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Vector type definitions
using VCa = blaze::CompressedVector<TypeA>;
using V5b = blaze::StaticVector<TypeB,5UL>;
// Creator type definitions
using CVCa = blazetest::Creator<VCa>;
using CV5b = blazetest::Creator<V5b>;
// Running the tests
for( size_t i=0UL; i<=8UL; ++i ) {
for( size_t j=0UL; j<=i; ++j ) {
RUN_SVECDVECOUTER_OPERATION_TEST( CVCa( i, j ), CV5b() );
}
}
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during sparse vector/dense vector outer product:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
#ifndef PYFLIGHTGOGGLESCLIENT_HPP
#define PYFLIGHTGOGGLESCLIENT_HPP
#include "pybind11/pybind11.h"
#include "pybind11/stl.h"
#include "pybind11/eigen.h"
#include "yaml-cpp/yaml.h"
#include "FlightGogglesClient.hpp"
typedef Eigen::Matrix<uchar, Eigen::Dynamic, 1> VectorXuc;
typedef Eigen::Matrix<double, Eigen::Dynamic, 1> VectorXd;
typedef Eigen::Matrix<int, Eigen::Dynamic, 1> VectorXi;
namespace py = pybind11;
class PyFlightGogglesClient{
public:
PyFlightGogglesClient() = default;
PyFlightGogglesClient(
std::string yaml_path,
std::string input_port,
std::string output_port);
void setCameraPose(const Eigen::Vector3d & pos, const Eigen::Vector4d & quat, int cam_index) {
Eigen::Affine3d camera_pose;
camera_pose.translation() = pos;
Eigen::Quaterniond q = Eigen::Quaterniond(quat[0], quat[1], quat[2], quat[3]);
camera_pose.linear() = q.normalized().toRotationMatrix();
flightGoggles->setCameraPoseUsingNEDCoordinates(camera_pose, cam_index);
}
void setObjectPose(const Eigen::Vector3d & pos, const Eigen::Vector4d & quat, int object_index) {
Eigen::Affine3d object_pose;
object_pose.translation() = pos;
Eigen::Quaterniond q = Eigen::Quaterniond(quat[0], quat[1], quat[2], quat[3]);
object_pose.linear() = q.normalized().toRotationMatrix();
flightGoggles->setObjectPoseUsingNEDCoordinates(object_pose, object_index);
}
void setCameraPoseUsingNEDCoordinates(const Eigen::Affine3d & ros_pose, int cam_index) {
flightGoggles->setCameraPoseUsingNEDCoordinates(ros_pose, cam_index);
}
void setObjectPoseUsingNEDCoordinates(const Eigen::Affine3d & ros_pose, int object_index) {
flightGoggles->setObjectPoseUsingNEDCoordinates(ros_pose, object_index);
}
void addCamera(std::string ID, int outputIndex, int shaderType=-1, bool hasCollisionCheck=true) {
unity_outgoing::Camera_t cam;
cam.ID = ID;
cam.outputShaderType = shaderType;
cam.hasCollisionCheck = hasCollisionCheck;
flightGoggles->state.cameras.push_back(cam);}
void addObject(std::string ID, std::string prefabID, double size_x, double size_y, double size_z) {
unity_outgoing::Object_t object;
object.ID = ID;
object.prefabID = prefabID;
object.size.resize(3);
object.size.at(0) = size_x;
object.size.at(1) = size_y;
object.size.at(2) = size_z;
flightGoggles->state.objects.push_back(object);
}
void setStateTime(int64_t timestamp) {
flightGoggles->state.ntime = timestamp;}
int64_t getTimestamp() {return flightGoggles->getTimestamp();}
bool requestRender() {return flightGoggles->requestRender();}
// std::map<std::string,VectorXuc> getImage();
std::tuple<std::map<std::string,VectorXi>, bool, std::map<std::string,VectorXd>, double> getImage();
void terminate() {flightGoggles->terminateConnections();}
private:
// FlightGogglesClient flightGoggles;
FlightGogglesClient* flightGoggles;
// Camera Info
float _f, _cx, _cy, _tx, _ty;
};
std::tuple<std::map<std::string,VectorXi>, bool, std::map<std::string,VectorXd>, double>
PyFlightGogglesClient::getImage(){
std::map<std::string, VectorXi> vec;
// const cv::Mat & img = cv::Mat::zeros(1024,768,CV_8UC3);
unity_incoming::RenderOutput_t rendered_output = flightGoggles->handleImageResponse();
for (auto i=0; i<rendered_output.renderMetadata.cameraIDs.size(); i++) {
//int * arr = rendered_output.images.at(i).isContinuous() ?
// rendered_output.images.at(i).data : rendered_output.images.at(i).clone().data;
int length = rendered_output.images.at(i).total()*rendered_output.images.at(i).channels();
int* arr;
arr = (int*) malloc(sizeof(int)*length);
if (rendered_output.renderMetadata.channels[i] == 2)
for (auto ii=0; ii<length;ii++) arr[ii] = rendered_output.images.at(i).at<uint16_t>(ii);
else
for (auto ii=0; ii<length;ii++) arr[ii] = rendered_output.images.at(i).at<uint8_t>(ii);
//memcpy(rendered_output.images.at(i).data, arr, sizeof(int)*length);
Eigen::Map<VectorXi> img_eigen(arr, length);
vec.insert(std::pair<std::string, VectorXi>
(rendered_output.renderMetadata.cameraIDs[i], img_eigen));
delete arr;
}
// Collision
bool hasCameraCollision = rendered_output.renderMetadata.hasCameraCollision;
// Landmark
std::map<std::string, VectorXd> landmark_t;
for (auto i=0; i<rendered_output.renderMetadata.landmarksInView.size(); i++) {
Eigen::VectorXd ld_pos_t = Eigen::Map<Eigen::VectorXd>(
rendered_output.renderMetadata.landmarksInView[i].position.data(),
rendered_output.renderMetadata.landmarksInView[i].position.size());
landmark_t.insert(std::pair<std::string, VectorXd>
(rendered_output.renderMetadata.landmarksInView[i].ID, ld_pos_t));
}
// Lidar
double lidarReturn = rendered_output.renderMetadata.lidarReturn;
// return vec;
return std::tuple<std::map<std::string,VectorXi>, bool, std::map<std::string,VectorXd>, double>
(vec, hasCameraCollision, landmark_t, lidarReturn);
}
void bind_FlightGogglesClient(py::module &m) {
py::class_<PyFlightGogglesClient>(m, "FlightGogglesClient")
.def(py::init<>())
.def(py::init<
std::string, std::string, std::string>(),
py::arg("yaml_path"),
py::arg("input_port")="10253",
py::arg("output_port")="10254")
.def("setCameraPose", &PyFlightGogglesClient::setCameraPose, "set camera pose")
.def("setCameraPoseUsingNEDCoordinates",
&PyFlightGogglesClient::setCameraPoseUsingNEDCoordinates,
"set camera pose using NED coordinates")
.def("setObjectPose", &PyFlightGogglesClient::setObjectPose, "set object pose")
.def("setObjectPoseUsingNEDCoordinates",
&PyFlightGogglesClient::setObjectPoseUsingNEDCoordinates,
"set object pose using NED coordinates")
.def("addCamera", &PyFlightGogglesClient::addCamera, "add camera")
.def("addObject", &PyFlightGogglesClient::addObject, "add object")
.def("setStateTime", &PyFlightGogglesClient::setStateTime, "set state timestamp")
.def("getTimestamp", &PyFlightGogglesClient::getTimestamp, "get state timestamp")
.def("requestRender", &PyFlightGogglesClient::requestRender, "request rendering")
.def("getImage", &PyFlightGogglesClient::getImage, "get image rendered")
.def("terminate", &PyFlightGogglesClient::terminate, "terminate connections");
}
#endif
|
assume cs:codesg
codesg segment
mov ax,0123H
mov bx,0456H
add ax,bx
add ax,ax
mov ax,4c00H
int 21H
codesg ends
end |
MODULE tms9918_generic_console
SECTION code_clib
EXTERN __tms9918_cls
PUBLIC __tms9918_scrollup
PUBLIC __tms9918_printc
PUBLIC __tms9918_set_ink
PUBLIC __tms9918_set_paper
PUBLIC __tms9918_set_attribute
EXTERN __tms9918_attribute
EXTERN __tms9918_text_xypos
EXTERN __tms9918_pattern_name
EXTERN generic_console_font32
EXTERN generic_console_udg32
EXTERN __console_w
EXTERN ansi_SCROLLUP
EXTERN ansi_cls
EXTERN __tms9918_map_colour
EXTERN generic_console_flags
EXTERN __tms9918_screen_mode
EXTERN __tms9918_scroll_buffer
EXTERN FILVRM
EXTERN LDIRVM
EXTERN LDIRMV
EXTERN CONSOLE_XOFFSET
EXTERN CONSOLE_YOFFSET
INCLUDE "video/tms9918/vdp.inc"
;
; The SPC-1000 has both a MC6847 and optionally a TMS9228A
;
; To support both we want the MC6847 to be the primary, and
; the VDP as the slave, so don't export the tms symbols as
; generic_console_*
;
; The Tatung Einstein has a TMS9928A as a main display and
; an 80 column 6845 as a secondary display.
;
IF VDP_EXPORT_DIRECT = 1
PUBLIC generic_console_cls
PUBLIC generic_console_scrollup
PUBLIC generic_console_printc
PUBLIC generic_console_set_ink
PUBLIC generic_console_set_paper
PUBLIC generic_console_set_attribute
defc generic_console_cls = __tms9918_cls
defc generic_console_scrollup = __tms9918_scrollup
defc generic_console_printc = __tms9918_printc
defc generic_console_set_ink = __tms9918_set_ink
defc generic_console_set_paper = __tms9918_set_paper
defc generic_console_set_attribute = __tms9918_set_attribute
ENDIF
__tms9918_set_attribute:
ret
__tms9918_set_ink:
call __tms9918_map_colour
rla
rla
rla
rla
and @11110000
ld b,0x0f
set_attr:
ld c,a
ld hl,__tms9918_attribute
ld a,(hl)
and b
or c
ld (hl),a
ret
__tms9918_set_paper:
call __tms9918_map_colour
and 15
ld b,0xf0
jr set_attr
__tms9918_scrollup:
push de
push bc
ld a,(__tms9918_screen_mode)
ld b,4
ld hl,40
and a
jr z,scroll_text
ld b,3
ld hl,32
cp 1
jr z,scroll_text
call ansi_SCROLLUP
scroll_rejoin:
pop bc
pop de
ret
; Entry: hl = width
scroll_text:
push ix
ld de,(__tms9918_pattern_name)
push hl ;Save width for later
add hl,de
scroll_text_1:
push bc
push hl ;Source
push de ;Destination
ld de,__tms9918_scroll_buffer
ld bc,256
call LDIRMV
pop de
push de
ld hl,__tms9918_scroll_buffer
ld bc,256
call LDIRVM
pop de ;Destination
pop hl
inc d
inc h
pop bc
djnz scroll_text_1
; And blank characters out
ld b,23
ld c,0
call __tms9918_text_xypos
pop bc
ld a,' '
call FILVRM
pop ix
jr scroll_rejoin
; c = x
; b = y
; a = d = character to print
; e = raw
__tms9918_printc:
push ix
ld a,(__tms9918_screen_mode)
cp 2
jr z,tms9918_printc_1
push de ;Save character
call __tms9918_text_xypos
pop de
ld a,d
ld bc,1
call FILVRM
pop ix
ret
tms9918_printc_1:
ld a,d
ld de,(generic_console_font32)
dec d
bit 7,a
jr z,tms9918_printc_rejoin
ld de,(generic_console_udg32)
res 7,a
tms9918_printc_rejoin:
ld l,a
ld h,0
add hl,hl
add hl,hl
add hl,hl
add hl,de
push bc ;Save coordinates
ld a,(generic_console_flags)
ld b,a ;Save flags
rlca
sbc a
ld c,a ;So c = 255/0 depending on inverse
ld de,__tms9918_scroll_buffer
push de ;Save buffer
ld a,8
copy_glyph:
ex af,af
ld a,(hl)
bit 4,b
jr z,not_bold
rrca
or (hl)
not_bold:
xor c ;Invert if necessary
ld (de),a
inc de
inc hl
ex af,af
dec a
jr nz,copy_glyph
bit 3,b
jr z,not_underline
dec de
dec a
ld (de),a
not_underline:
pop hl ;Get buffer back
pop bc
ld a,c
add CONSOLE_XOFFSET
add a
add a
add a
ld e,a
ld a,CONSOLE_YOFFSET
add b
ld d,a
push de
ld bc,8
call LDIRVM
pop hl
; Now set the attributes
ld de,8192
add hl,de
ld a,(__tms9918_attribute)
ld bc,8
call FILVRM
pop ix
ret
|
; A040387: Continued fraction for sqrt(408).
; 20,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40,5,40
pow $0,4
mov $1,$0
trn $1,4
sub $1,4
gcd $0,$1
mul $0,5
|
sta {m1}
lda #0
sta {m1}+1
sta {m1}+2
sta {m1}+3
|
;
; SD Card driver
; Taken from the OSCA Bootcode by Phil Ruston 2011
; Port by Stefano Bodrato, 2012
;
; Read card information details
;
; $Id: sd_read_csd.asm,v 1.2 2015/01/19 01:33:07 pauloscustodio Exp $
;
PUBLIC sd_read_csd
EXTERN sector_buffer_loc
EXTERN sd_send_command_null_args
EXTERN sd_wait_data_token
EXTERN sd_read_bytes_to_sector_buffer
INCLUDE "sdcard.def"
; Returns BC:DE = Total capacity of card (in sectors)
sd_read_csd:
ld a,CMD9 ; send "read CSD" command: 49 00 00 00 00 01 to read card info
call sd_send_command_null_args
ld a,sd_error_bad_command_response
ret nz ; ZF set if command response = 00
call sd_wait_data_token ; wait for the data token
ld a,sd_error_data_token_timeout
ret nz
sd_id_ok:
ld b,18 ; read the card info to sector buffer (16 bytes + 2 CRC)
call sd_read_bytes_to_sector_buffer
ld ix,(sector_buffer_loc) ; compute card's capacity
bit 6,(ix)
jr z,sd_csd_v1
sd_csd_v2:
ld l,(ix+9) ; for CSD v2.00
ld h,(ix+8)
inc hl
ld a,10
ld bc,0
sd_csd2lp:
add hl,hl
rl c
rl b
dec a
jr nz,sd_csd2lp
ex de,hl ; Return Capacity (number of sectors) in BC:DE
xor a
ret
sd_csd_v1:
ld a,(ix+6) ; For CSD v1.00
and @00000011
ld d,a
ld e,(ix+7)
ld a,(ix+8)
and @11000000
sla a
rl e
rl d
sla a
rl e
rl d ; DE = 12 bit value: "C_SIZE"
ld a,(ix+9)
and @00000011
ld b,a
ld a,(ix+10)
and @10000000
sla a
rl b ; B = 3 bit value: "C_MULT"
inc b
inc b
ld hl,0
sd_cmsh:
sla e
rl d
rl l
rl h
djnz sd_cmsh ; HL:DE = ("C_MULT"+1) * (2 ^ (C_MULT+2))
ld a,(ix+5)
and @00001111 ; A = "READ_BL_LEN"
jr z,sd_nbls
ld b,a
sd_blsh:
sla e
rl d
rl l
rl h
djnz sd_blsh ; Cap (bytes) HL:DE = ("C_MULT"+1) * (2 ^ (C_MULT+2)) * (2^READ_BL_LEN)
ld b,9 ; convert number of bytes to numer of sectors
sd_cbsec:
srl h
rr l
rr d
rr e
djnz sd_cbsec
sd_nbls:
push hl
pop bc ; Return Capacity (number of sectors) in BC:DE
xor a
ret
|
; A044504: Numbers n such that string 3,3 occurs in the base 6 representation of n but not of n+1.
; 21,57,93,131,165,201,237,273,309,347,381,417,453,489,525,563,597,633,669,705,741,791,813,849,885,921,957,995,1029,1065,1101,1137,1173,1211,1245,1281,1317,1353,1389,1427,1461,1497,1533,1569,1605,1643,1677,1713
mov $2,$0
mov $3,$0
add $0,3
gcd $0,6
lpb $0,1
div $0,2
sub $0,4
gcd $3,7
mov $1,$3
lpe
mul $1,2
add $1,21
mov $4,$2
mul $4,36
add $1,$4
|
/**
* Copyright (c) 2017 Melown Technologies SE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * 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.
*
* 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.
*/
#ifndef vtslibs_vts_tileset_driver_plain_hpp_included_
#define vtslibs_vts_tileset_driver_plain_hpp_included_
#include <set>
#include <map>
#include <memory>
#include "../driver.hpp"
#include "cache.hpp"
namespace vtslibs { namespace vts { namespace driver {
class PlainDriver : public Driver {
public:
typedef std::shared_ptr<PlainDriver> pointer;
/** Creates new storage. Existing storage is overwritten only if mode ==
* CreateMode::overwrite.
*/
PlainDriver(const boost::filesystem::path &root
, const PlainOptions &options
, const CloneOptions &cloneOptions);
/** Opens storage.
*/
PlainDriver(const boost::filesystem::path &root
, const OpenOptions &openOptions
, const PlainOptions &options);
virtual ~PlainDriver();
/** Reencodes plain tileset.
* Always returns false.
*/
static bool reencode(const boost::filesystem::path &root
, const PlainOptions &driverOptions
, const ReencodeOptions &options
, const std::string &prefix = "");
private:
virtual OStream::pointer output_impl(const File type);
virtual IStream::pointer input_impl(File type) const;
virtual IStream::pointer input_impl(File type, const NullWhenNotFound_t&)
const;
virtual OStream::pointer
output_impl(const TileId &tileId, TileFile type);
virtual IStream::pointer
input_impl(const TileId &tileId, TileFile type) const;
virtual IStream::pointer
input_impl(const TileId &tileId, TileFile type, const NullWhenNotFound_t&)
const;
virtual void drop_impl();
virtual void flush_impl();
virtual FileStat stat_impl(File type) const;
virtual FileStat stat_impl(const TileId &tileId, TileFile type) const;
virtual Resources resources_impl() const;
virtual Driver::pointer
clone_impl(const boost::filesystem::path &root
, const CloneOptions &cloneOptions) const;
virtual std::string info_impl() const;
mutable driver::Cache cache_;
};
} } } // namespace vtslibs::vts::driver
#endif // vtslibs_vts_tileset_driver_plain_hpp_included_
|
/*
* hidl interface for wpa_supplicant daemon
* Copyright (c) 2004-2016, Jouni Malinen <j@w1.fi>
* Copyright (c) 2004-2016, Roshan Pius <rpius@google.com>
* Copyright (C) 2017 Sony Mobile Communications Inc.
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
*/
#include "hidl_manager.h"
#include "hidl_return_util.h"
#include "iface_config_utils.h"
#include "misc_utils.h"
#include "p2p_iface.h"
#include "sta_network.h"
extern "C"
{
#include "ap.h"
#include "wps_supplicant.h"
#include "wifi_display.h"
#include "utils/eloop.h"
#include "wpa_supplicant_i.h"
#include "driver_i.h"
}
#define P2P_MAX_JOIN_SCAN_ATTEMPTS 10
namespace {
const char kConfigMethodStrPbc[] = "pbc";
const char kConfigMethodStrDisplay[] = "display";
const char kConfigMethodStrKeypad[] = "keypad";
constexpr char kSetMiracastMode[] = "MIRACAST ";
constexpr uint8_t kWfdDeviceInfoSubelemId = 0;
constexpr char kWfdDeviceInfoSubelemLenHexStr[] = "0006";
std::function<void()> pending_join_scan_callback = NULL;
std::function<void()> pending_scan_res_join_callback = NULL;
using android::hardware::wifi::supplicant::V1_0::ISupplicantP2pIface;
using android::hardware::wifi::supplicant::V1_0::ISupplicantStaNetwork;
uint8_t convertHidlMiracastModeToInternal(
ISupplicantP2pIface::MiracastMode mode)
{
switch (mode) {
case ISupplicantP2pIface::MiracastMode::DISABLED:
return 0;
case ISupplicantP2pIface::MiracastMode::SOURCE:
return 1;
case ISupplicantP2pIface::MiracastMode::SINK:
return 2;
};
WPA_ASSERT(false);
}
/**
* Check if the provided ssid is valid or not.
*
* Returns 1 if valid, 0 otherwise.
*/
int isSsidValid(const std::vector<uint8_t>& ssid)
{
if (ssid.size() == 0 ||
ssid.size() >
static_cast<uint32_t>(ISupplicantStaNetwork::ParamSizeLimits::
SSID_MAX_LEN_IN_BYTES)) {
return 0;
}
return 1;
}
/**
* Check if the provided psk passhrase is valid or not.
*
* Returns 1 if valid, 0 otherwise.
*/
int isPskPassphraseValid(const std::string &psk)
{
if (psk.size() <
static_cast<uint32_t>(ISupplicantStaNetwork::ParamSizeLimits::
PSK_PASSPHRASE_MIN_LEN_IN_BYTES) ||
psk.size() >
static_cast<uint32_t>(ISupplicantStaNetwork::ParamSizeLimits::
PSK_PASSPHRASE_MAX_LEN_IN_BYTES)) {
return 0;
}
if (has_ctrl_char((u8 *)psk.c_str(), psk.size())) {
return 0;
}
return 1;
}
void setBandScanFreqsList(
struct wpa_supplicant *wpa_s,
enum hostapd_hw_mode band,
struct wpa_driver_scan_params *params)
{
/* Include only supported channels for the specified band */
struct hostapd_hw_modes *mode;
int count, i;
mode = get_mode(wpa_s->hw.modes, wpa_s->hw.num_modes, band, 0);
if (mode == NULL) {
/* No channels supported in this band. */
return;
}
params->freqs = (int *) os_calloc(mode->num_channels + 1, sizeof(int));
if (params->freqs == NULL)
return;
for (count = 0, i = 0; i < mode->num_channels; i++) {
if (mode->channels[i].flag & HOSTAPD_CHAN_DISABLED)
continue;
params->freqs[count++] = mode->channels[i].freq;
}
}
/*
* isAnyEtherAddr - match any ether address
*
*/
int isAnyEtherAddr(const u8 *a)
{
// 02:00:00:00:00:00
return (a[0] == 2) && !(a[1] | a[2] | a[3] | a[4] | a[5]);
}
/**
* findBssBySsid - Fetch a BSS table entry based on SSID and optional BSSID.
* @wpa_s: Pointer to wpa_supplicant data
* @bssid: BSSID, 02:00:00:00:00:00 matches any bssid
* @ssid: SSID
* @ssid_len: Length of @ssid
* Returns: Pointer to the BSS entry or %NULL if not found
*/
struct wpa_bss* findBssBySsid(
struct wpa_supplicant *wpa_s, const u8 *bssid,
const u8 *ssid, size_t ssid_len)
{
struct wpa_bss *bss;
dl_list_for_each(bss, &wpa_s->bss, struct wpa_bss, list) {
if ((isAnyEtherAddr(bssid) ||
os_memcmp(bss->bssid, bssid, ETH_ALEN) == 0) &&
bss->ssid_len == ssid_len &&
os_memcmp(bss->ssid, ssid, ssid_len) == 0)
return bss;
}
return NULL;
}
struct wpa_ssid* addGroupClientNetwork(
struct wpa_supplicant* wpa_s,
uint8_t *group_owner_bssid,
const std::vector<uint8_t>& ssid,
const std::string& passphrase)
{
struct wpa_ssid* wpa_network = wpa_config_add_network(wpa_s->conf);
if (!wpa_network) {
return NULL;
}
// set general network defaults
wpa_config_set_network_defaults(wpa_network);
// set P2p network defaults
wpa_network->p2p_group = 1;
wpa_network->mode = wpas_mode::WPAS_MODE_INFRA;
wpa_network->auth_alg = WPA_AUTH_ALG_OPEN;
wpa_network->key_mgmt = WPA_KEY_MGMT_PSK;
wpa_network->proto = WPA_PROTO_RSN;
wpa_network->pairwise_cipher = WPA_CIPHER_CCMP;
wpa_network->group_cipher = WPA_CIPHER_CCMP;
wpa_network->disabled = 2;
// set necessary fields
os_memcpy(wpa_network->bssid, group_owner_bssid, ETH_ALEN);
wpa_network->bssid_set = 1;
wpa_network->ssid = (uint8_t *)os_malloc(ssid.size());
if (wpa_network->ssid == NULL) {
wpa_config_remove_network(wpa_s->conf, wpa_network->id);
return NULL;
}
memcpy(wpa_network->ssid, ssid.data(), ssid.size());
wpa_network->ssid_len = ssid.size();
wpa_network->psk_set = 0;
wpa_network->passphrase = dup_binstr(passphrase.c_str(), passphrase.length());
if (wpa_network->passphrase == NULL) {
wpa_config_remove_network(wpa_s->conf, wpa_network->id);
return NULL;
}
wpa_config_update_psk(wpa_network);
return wpa_network;
}
void joinScanWrapper(void *eloop_ctx, void *timeout_ctx)
{
struct wpa_supplicant *wpa_s = (struct wpa_supplicant *) eloop_ctx;
if (pending_join_scan_callback != NULL) {
pending_join_scan_callback();
}
}
void scanResJoinWrapper(
struct wpa_supplicant *wpa_s,
struct wpa_scan_results *scan_res)
{
if (wpa_s->p2p_scan_work) {
struct wpa_radio_work *work = wpa_s->p2p_scan_work;
wpa_s->p2p_scan_work = NULL;
radio_work_done(work);
}
if (pending_scan_res_join_callback) {
pending_scan_res_join_callback();
}
}
int joinScanReq(
struct wpa_supplicant* wpa_s,
const std::vector<uint8_t>& ssid,
int freq)
{
int ret;
struct wpa_driver_scan_params params;
struct wpabuf *ies;
size_t ielen;
unsigned int bands;
if (wpa_s->global->p2p == NULL || wpa_s->global->p2p_disabled) {
wpa_printf(MSG_ERROR,
"P2P: P2P interface is gone, cancel join scan");
return -ENXIO;
}
os_memset(¶ms, 0, sizeof(params));
if (ssid.size() > 0) {
params.ssids[0].ssid = ssid.data();
params.ssids[0].ssid_len = ssid.size();
} else {
params.ssids[0].ssid = (u8 *) P2P_WILDCARD_SSID;
params.ssids[0].ssid_len = P2P_WILDCARD_SSID_LEN;
}
wpa_printf(MSG_DEBUG, "Scan SSID %s for join with frequency %d (reinvoke)",
wpa_ssid_txt(params.ssids[0].ssid, params.ssids[0].ssid_len), freq);
if (freq > 0) {
if (freq == 2 || freq == 5) {
if (wpa_s->hw.modes != NULL) {
switch (freq) {
case 2:
setBandScanFreqsList(wpa_s,
HOSTAPD_MODE_IEEE80211G, ¶ms);
break;
case 5:
setBandScanFreqsList(wpa_s,
HOSTAPD_MODE_IEEE80211A, ¶ms);
break;
}
if (!params.freqs) {
wpa_printf(MSG_ERROR,
"P2P: No supported channels in %dG band.", freq);
return -1;
}
} else {
wpa_printf(MSG_DEBUG,
"P2P: Unknown what %dG channels the driver supports.", freq);
}
} else {
if (0 == p2p_supported_freq_cli(wpa_s->global->p2p, freq)) {
wpa_printf(MSG_ERROR,
"P2P: freq %d is not supported for a client.", freq);
return -1;
}
/*
* Allocate memory for frequency array, allocate one extra
* slot for the zero-terminator.
*/
params.freqs = (int *) os_calloc(2, sizeof(int));
if (params.freqs) {
params.freqs[0] = freq;
} else {
wpa_printf(MSG_ERROR,
"P2P: Cannot allocate memory for scan params.");
return -1;
}
}
}
ielen = p2p_scan_ie_buf_len(wpa_s->global->p2p);
ies = wpabuf_alloc(ielen);
if (ies == NULL) {
if (params.freqs) {
os_free(params.freqs);
}
return -1;
}
bands = wpas_get_bands(wpa_s, params.freqs);
p2p_scan_ie(wpa_s->global->p2p, ies, NULL, bands);
params.p2p_probe = 1;
params.extra_ies = (u8 *) wpabuf_head(ies);
params.extra_ies_len = wpabuf_len(ies);
if (wpa_s->clear_driver_scan_cache) {
wpa_printf(MSG_DEBUG,
"Request driver to clear scan cache due to local BSS flush");
params.only_new_results = 1;
}
ret = wpa_drv_scan(wpa_s, ¶ms);
if (!ret) {
os_get_reltime(&wpa_s->scan_trigger_time);
if (wpa_s->scan_res_handler) {
wpa_printf(MSG_DEBUG, "Replace current running scan result handler");
}
wpa_s->scan_res_handler = scanResJoinWrapper;
wpa_s->own_scan_requested = 1;
wpa_s->clear_driver_scan_cache = 0;
}
if (params.freqs) {
os_free(params.freqs);
}
wpabuf_free(ies);
return ret;
}
int joinGroup(
struct wpa_supplicant* wpa_s,
uint8_t *group_owner_bssid,
const std::vector<uint8_t>& ssid,
const std::string& passphrase)
{
int ret = 0;
int he = wpa_s->conf->p2p_go_he;
int vht = wpa_s->conf->p2p_go_vht;
int ht40 = wpa_s->conf->p2p_go_ht40 || vht;
// Construct a network for adding group.
// Group client follows the persistent attribute of Group Owner.
// If joined group is persistent, it adds a persistent network on GroupStarted.
struct wpa_ssid *wpa_network = addGroupClientNetwork(
wpa_s, group_owner_bssid, ssid, passphrase);
if (wpa_network == NULL) {
wpa_printf(MSG_ERROR, "P2P: Cannot construct a network for group join.");
return -1;
}
// this is temporary network only for establishing the connection.
wpa_network->temporary = 1;
if (wpas_p2p_group_add_persistent(
wpa_s, wpa_network, 0, 0, 0, 0, ht40, vht,
CHANWIDTH_USE_HT, he, 0, NULL, 0, 0)) {
ret = -1;
}
// Always remove this temporary network at the end.
wpa_config_remove_network(wpa_s->conf, wpa_network->id);
return ret;
}
void notifyGroupJoinFailure(
struct wpa_supplicant* wpa_s)
{
u8 zero_addr[ETH_ALEN] = {0};
std::vector<uint8_t> ssid = {'D', 'I', 'R', 'E','C', 'T', '-'};
std::string passphrase = "";
struct wpa_ssid *wpa_network = addGroupClientNetwork(
wpa_s, zero_addr, ssid, passphrase);
if (wpa_network) {
wpa_network->temporary = 1;
wpas_notify_p2p_group_formation_failure(wpa_s, "Failed to find the group.");
wpas_notify_p2p_group_removed(
wpa_s, wpa_network, "client");
wpa_config_remove_network(
wpa_s->conf, wpa_network->id);
} else {
wpa_printf(MSG_ERROR,
"P2P: Cannot construct a network.");
}
}
void scanResJoinIgnore(struct wpa_supplicant *wpa_s, struct wpa_scan_results *scan_res) {
wpa_printf(MSG_DEBUG, "P2P: Ignore group join scan results.");
if (wpa_s->p2p_scan_work) {
struct wpa_radio_work *work = wpa_s->p2p_scan_work;
wpa_s->p2p_scan_work = NULL;
radio_work_done(work);
}
}
} // namespace
namespace android {
namespace hardware {
namespace wifi {
namespace supplicant {
namespace V1_3 {
namespace implementation {
using hidl_return_util::validateAndCall;
using V1_0::SupplicantStatusCode;
P2pIface::P2pIface(struct wpa_global* wpa_global, const char ifname[])
: wpa_global_(wpa_global), ifname_(ifname), is_valid_(true)
{}
void P2pIface::invalidate() { is_valid_ = false; }
bool P2pIface::isValid()
{
return (is_valid_ && (retrieveIfacePtr() != nullptr));
}
Return<void> P2pIface::getName(getName_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::getNameInternal, _hidl_cb);
}
Return<void> P2pIface::getType(getType_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::getTypeInternal, _hidl_cb);
}
Return<void> P2pIface::addNetwork(addNetwork_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::addNetworkInternal, _hidl_cb);
}
Return<void> P2pIface::removeNetwork(
SupplicantNetworkId id, removeNetwork_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::removeNetworkInternal, _hidl_cb, id);
}
Return<void> P2pIface::getNetwork(
SupplicantNetworkId id, getNetwork_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::getNetworkInternal, _hidl_cb, id);
}
Return<void> P2pIface::listNetworks(listNetworks_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::listNetworksInternal, _hidl_cb);
}
Return<void> P2pIface::registerCallback(
const sp<ISupplicantP2pIfaceCallback>& callback,
registerCallback_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::registerCallbackInternal, _hidl_cb, callback);
}
Return<void> P2pIface::getDeviceAddress(getDeviceAddress_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::getDeviceAddressInternal, _hidl_cb);
}
Return<void> P2pIface::setSsidPostfix(
const hidl_vec<uint8_t>& postfix, setSsidPostfix_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::setSsidPostfixInternal, _hidl_cb, postfix);
}
Return<void> P2pIface::setGroupIdle(
const hidl_string& group_ifname, uint32_t timeout_in_sec,
setGroupIdle_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::setGroupIdleInternal, _hidl_cb, group_ifname,
timeout_in_sec);
}
Return<void> P2pIface::setPowerSave(
const hidl_string& group_ifname, bool enable, setPowerSave_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::setPowerSaveInternal, _hidl_cb, group_ifname, enable);
}
Return<void> P2pIface::find(uint32_t timeout_in_sec, find_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::findInternal, _hidl_cb, timeout_in_sec);
}
Return<void> P2pIface::stopFind(stopFind_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::stopFindInternal, _hidl_cb);
}
Return<void> P2pIface::flush(flush_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::flushInternal, _hidl_cb);
}
Return<void> P2pIface::connect(
const hidl_array<uint8_t, 6>& peer_address,
ISupplicantP2pIface::WpsProvisionMethod provision_method,
const hidl_string& pre_selected_pin, bool join_existing_group,
bool persistent, uint32_t go_intent, connect_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::connectInternal, _hidl_cb, peer_address,
provision_method, pre_selected_pin, join_existing_group, persistent,
go_intent);
}
Return<void> P2pIface::cancelConnect(cancelConnect_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::cancelConnectInternal, _hidl_cb);
}
Return<void> P2pIface::provisionDiscovery(
const hidl_array<uint8_t, 6>& peer_address,
ISupplicantP2pIface::WpsProvisionMethod provision_method,
provisionDiscovery_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::provisionDiscoveryInternal, _hidl_cb, peer_address,
provision_method);
}
Return<void> P2pIface::addGroup(
bool persistent, SupplicantNetworkId persistent_network_id,
addGroup_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::addGroupInternal, _hidl_cb, persistent,
persistent_network_id);
}
Return<void> P2pIface::removeGroup(
const hidl_string& group_ifname, removeGroup_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::removeGroupInternal, _hidl_cb, group_ifname);
}
Return<void> P2pIface::reject(
const hidl_array<uint8_t, 6>& peer_address, reject_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::rejectInternal, _hidl_cb, peer_address);
}
Return<void> P2pIface::invite(
const hidl_string& group_ifname,
const hidl_array<uint8_t, 6>& go_device_address,
const hidl_array<uint8_t, 6>& peer_address, invite_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::inviteInternal, _hidl_cb, group_ifname,
go_device_address, peer_address);
}
Return<void> P2pIface::reinvoke(
SupplicantNetworkId persistent_network_id,
const hidl_array<uint8_t, 6>& peer_address, reinvoke_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::reinvokeInternal, _hidl_cb, persistent_network_id,
peer_address);
}
Return<void> P2pIface::configureExtListen(
uint32_t period_in_millis, uint32_t interval_in_millis,
configureExtListen_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::configureExtListenInternal, _hidl_cb, period_in_millis,
interval_in_millis);
}
Return<void> P2pIface::setListenChannel(
uint32_t channel, uint32_t operating_class, setListenChannel_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::setListenChannelInternal, _hidl_cb, channel,
operating_class);
}
Return<void> P2pIface::setDisallowedFrequencies(
const hidl_vec<FreqRange>& ranges, setDisallowedFrequencies_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::setDisallowedFrequenciesInternal, _hidl_cb, ranges);
}
Return<void> P2pIface::getSsid(
const hidl_array<uint8_t, 6>& peer_address, getSsid_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::getSsidInternal, _hidl_cb, peer_address);
}
Return<void> P2pIface::getGroupCapability(
const hidl_array<uint8_t, 6>& peer_address, getGroupCapability_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::getGroupCapabilityInternal, _hidl_cb, peer_address);
}
Return<void> P2pIface::addBonjourService(
const hidl_vec<uint8_t>& query, const hidl_vec<uint8_t>& response,
addBonjourService_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::addBonjourServiceInternal, _hidl_cb, query, response);
}
Return<void> P2pIface::removeBonjourService(
const hidl_vec<uint8_t>& query, removeBonjourService_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::removeBonjourServiceInternal, _hidl_cb, query);
}
Return<void> P2pIface::addUpnpService(
uint32_t version, const hidl_string& service_name,
addUpnpService_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::addUpnpServiceInternal, _hidl_cb, version, service_name);
}
Return<void> P2pIface::removeUpnpService(
uint32_t version, const hidl_string& service_name,
removeUpnpService_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::removeUpnpServiceInternal, _hidl_cb, version,
service_name);
}
Return<void> P2pIface::flushServices(flushServices_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::flushServicesInternal, _hidl_cb);
}
Return<void> P2pIface::requestServiceDiscovery(
const hidl_array<uint8_t, 6>& peer_address, const hidl_vec<uint8_t>& query,
requestServiceDiscovery_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::requestServiceDiscoveryInternal, _hidl_cb, peer_address,
query);
}
Return<void> P2pIface::cancelServiceDiscovery(
uint64_t identifier, cancelServiceDiscovery_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::cancelServiceDiscoveryInternal, _hidl_cb, identifier);
}
Return<void> P2pIface::setMiracastMode(
ISupplicantP2pIface::MiracastMode mode, setMiracastMode_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::setMiracastModeInternal, _hidl_cb, mode);
}
Return<void> P2pIface::startWpsPbc(
const hidl_string& group_ifname, const hidl_array<uint8_t, 6>& bssid,
startWpsPbc_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::startWpsPbcInternal, _hidl_cb, group_ifname, bssid);
}
Return<void> P2pIface::startWpsPinKeypad(
const hidl_string& group_ifname, const hidl_string& pin,
startWpsPinKeypad_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::startWpsPinKeypadInternal, _hidl_cb, group_ifname, pin);
}
Return<void> P2pIface::startWpsPinDisplay(
const hidl_string& group_ifname, const hidl_array<uint8_t, 6>& bssid,
startWpsPinDisplay_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::startWpsPinDisplayInternal, _hidl_cb, group_ifname,
bssid);
}
Return<void> P2pIface::cancelWps(
const hidl_string& group_ifname, cancelWps_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::cancelWpsInternal, _hidl_cb, group_ifname);
}
Return<void> P2pIface::setWpsDeviceName(
const hidl_string& name, setWpsDeviceName_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::setWpsDeviceNameInternal, _hidl_cb, name);
}
Return<void> P2pIface::setWpsDeviceType(
const hidl_array<uint8_t, 8>& type, setWpsDeviceType_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::setWpsDeviceTypeInternal, _hidl_cb, type);
}
Return<void> P2pIface::setWpsManufacturer(
const hidl_string& manufacturer, setWpsManufacturer_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::setWpsManufacturerInternal, _hidl_cb, manufacturer);
}
Return<void> P2pIface::setWpsModelName(
const hidl_string& model_name, setWpsModelName_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::setWpsModelNameInternal, _hidl_cb, model_name);
}
Return<void> P2pIface::setWpsModelNumber(
const hidl_string& model_number, setWpsModelNumber_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::setWpsModelNumberInternal, _hidl_cb, model_number);
}
Return<void> P2pIface::setWpsSerialNumber(
const hidl_string& serial_number, setWpsSerialNumber_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::setWpsSerialNumberInternal, _hidl_cb, serial_number);
}
Return<void> P2pIface::setWpsConfigMethods(
uint16_t config_methods, setWpsConfigMethods_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::setWpsConfigMethodsInternal, _hidl_cb, config_methods);
}
Return<void> P2pIface::enableWfd(bool enable, enableWfd_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::enableWfdInternal, _hidl_cb, enable);
}
Return<void> P2pIface::setWfdDeviceInfo(
const hidl_array<uint8_t, 6>& info, setWfdDeviceInfo_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::setWfdDeviceInfoInternal, _hidl_cb, info);
}
Return<void> P2pIface::createNfcHandoverRequestMessage(
createNfcHandoverRequestMessage_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::createNfcHandoverRequestMessageInternal, _hidl_cb);
}
Return<void> P2pIface::createNfcHandoverSelectMessage(
createNfcHandoverSelectMessage_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::createNfcHandoverSelectMessageInternal, _hidl_cb);
}
Return<void> P2pIface::reportNfcHandoverResponse(
const hidl_vec<uint8_t>& request, reportNfcHandoverResponse_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::reportNfcHandoverResponseInternal, _hidl_cb, request);
}
Return<void> P2pIface::reportNfcHandoverInitiation(
const hidl_vec<uint8_t>& select, reportNfcHandoverInitiation_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::reportNfcHandoverInitiationInternal, _hidl_cb, select);
}
Return<void> P2pIface::saveConfig(saveConfig_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::saveConfigInternal, _hidl_cb);
}
Return<void> P2pIface::addGroup_1_2(
const hidl_vec<uint8_t>& ssid, const hidl_string& passphrase,
bool persistent, uint32_t freq, const hidl_array<uint8_t, 6>& peer_address,
bool join, addGroup_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::addGroup_1_2Internal, _hidl_cb,
ssid, passphrase, persistent, freq, peer_address, join);
}
Return<void> P2pIface::setMacRandomization(bool enable, setMacRandomization_cb _hidl_cb)
{
return validateAndCall(
this, SupplicantStatusCode::FAILURE_IFACE_INVALID,
&P2pIface::setMacRandomizationInternal, _hidl_cb, enable);
}
std::pair<SupplicantStatus, std::string> P2pIface::getNameInternal()
{
return {{SupplicantStatusCode::SUCCESS, ""}, ifname_};
}
std::pair<SupplicantStatus, IfaceType> P2pIface::getTypeInternal()
{
return {{SupplicantStatusCode::SUCCESS, ""}, IfaceType::P2P};
}
std::pair<SupplicantStatus, sp<ISupplicantP2pNetwork>>
P2pIface::addNetworkInternal()
{
android::sp<ISupplicantP2pNetwork> network;
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
struct wpa_ssid* ssid = wpa_supplicant_add_network(wpa_s);
if (!ssid) {
return {{SupplicantStatusCode::FAILURE_UNKNOWN, ""}, network};
}
HidlManager* hidl_manager = HidlManager::getInstance();
if (!hidl_manager ||
hidl_manager->getP2pNetworkHidlObjectByIfnameAndNetworkId(
wpa_s->ifname, ssid->id, &network)) {
return {{SupplicantStatusCode::FAILURE_UNKNOWN, ""}, network};
}
return {{SupplicantStatusCode::SUCCESS, ""}, network};
}
SupplicantStatus P2pIface::removeNetworkInternal(SupplicantNetworkId id)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
int result = wpa_supplicant_remove_network(wpa_s, id);
if (result == -1) {
return {SupplicantStatusCode::FAILURE_NETWORK_UNKNOWN, ""};
}
if (result != 0) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
std::pair<SupplicantStatus, sp<ISupplicantP2pNetwork>>
P2pIface::getNetworkInternal(SupplicantNetworkId id)
{
android::sp<ISupplicantP2pNetwork> network;
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
struct wpa_ssid* ssid = wpa_config_get_network(wpa_s->conf, id);
if (!ssid) {
return {{SupplicantStatusCode::FAILURE_NETWORK_UNKNOWN, ""},
network};
}
HidlManager* hidl_manager = HidlManager::getInstance();
if (!hidl_manager ||
hidl_manager->getP2pNetworkHidlObjectByIfnameAndNetworkId(
wpa_s->ifname, ssid->id, &network)) {
return {{SupplicantStatusCode::FAILURE_UNKNOWN, ""}, network};
}
return {{SupplicantStatusCode::SUCCESS, ""}, network};
}
std::pair<SupplicantStatus, std::vector<SupplicantNetworkId>>
P2pIface::listNetworksInternal()
{
std::vector<SupplicantNetworkId> network_ids;
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
for (struct wpa_ssid* wpa_ssid = wpa_s->conf->ssid; wpa_ssid;
wpa_ssid = wpa_ssid->next) {
network_ids.emplace_back(wpa_ssid->id);
}
return {{SupplicantStatusCode::SUCCESS, ""}, std::move(network_ids)};
}
SupplicantStatus P2pIface::registerCallbackInternal(
const sp<ISupplicantP2pIfaceCallback>& callback)
{
HidlManager* hidl_manager = HidlManager::getInstance();
if (!hidl_manager ||
hidl_manager->addP2pIfaceCallbackHidlObject(ifname_, callback)) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
std::pair<SupplicantStatus, std::array<uint8_t, 6>>
P2pIface::getDeviceAddressInternal()
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
std::array<uint8_t, 6> addr;
static_assert(ETH_ALEN == addr.size(), "Size mismatch");
os_memcpy(addr.data(), wpa_s->global->p2p_dev_addr, ETH_ALEN);
return {{SupplicantStatusCode::SUCCESS, ""}, addr};
}
SupplicantStatus P2pIface::setSsidPostfixInternal(
const std::vector<uint8_t>& postfix)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
if (p2p_set_ssid_postfix(
wpa_s->global->p2p, postfix.data(), postfix.size())) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::setGroupIdleInternal(
const std::string& group_ifname, uint32_t timeout_in_sec)
{
struct wpa_supplicant* wpa_group_s =
retrieveGroupIfacePtr(group_ifname);
if (!wpa_group_s) {
return {SupplicantStatusCode::FAILURE_IFACE_UNKNOWN, ""};
}
wpa_group_s->conf->p2p_group_idle = timeout_in_sec;
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::setPowerSaveInternal(
const std::string& group_ifname, bool enable)
{
struct wpa_supplicant* wpa_group_s =
retrieveGroupIfacePtr(group_ifname);
if (!wpa_group_s) {
return {SupplicantStatusCode::FAILURE_IFACE_UNKNOWN, ""};
}
if (wpa_drv_set_p2p_powersave(wpa_group_s, enable, -1, -1)) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::findInternal(uint32_t timeout_in_sec)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
if (wpa_s->wpa_state == WPA_INTERFACE_DISABLED) {
return {SupplicantStatusCode::FAILURE_IFACE_DISABLED, ""};
}
uint32_t search_delay = wpas_p2p_search_delay(wpa_s);
if (wpas_p2p_find(
wpa_s, timeout_in_sec, P2P_FIND_START_WITH_FULL, 0, nullptr,
nullptr, search_delay, 0, nullptr, 0)) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::stopFindInternal()
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
if (wpa_s->wpa_state == WPA_INTERFACE_DISABLED) {
return {SupplicantStatusCode::FAILURE_IFACE_DISABLED, ""};
}
if (wpa_s->scan_res_handler == scanResJoinWrapper) {
wpa_printf(MSG_DEBUG, "P2P: Stop pending group scan for stopping find).");
pending_scan_res_join_callback = NULL;
wpa_s->scan_res_handler = scanResJoinIgnore;
}
wpas_p2p_stop_find(wpa_s);
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::flushInternal()
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
os_memset(wpa_s->p2p_auth_invite, 0, ETH_ALEN);
wpa_s->force_long_sd = 0;
wpas_p2p_stop_find(wpa_s);
wpa_s->parent->p2ps_method_config_any = 0;
if (wpa_s->global->p2p)
p2p_flush(wpa_s->global->p2p);
return {SupplicantStatusCode::SUCCESS, ""};
}
// This method only implements support for subset (needed by Android framework)
// of parameters that can be specified for connect.
std::pair<SupplicantStatus, std::string> P2pIface::connectInternal(
const std::array<uint8_t, 6>& peer_address,
ISupplicantP2pIface::WpsProvisionMethod provision_method,
const std::string& pre_selected_pin, bool join_existing_group,
bool persistent, uint32_t go_intent)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
if (go_intent > 15) {
return {{SupplicantStatusCode::FAILURE_ARGS_INVALID, ""}, {}};
}
int go_intent_signed = join_existing_group ? -1 : go_intent;
p2p_wps_method wps_method = {};
switch (provision_method) {
case WpsProvisionMethod::PBC:
wps_method = WPS_PBC;
break;
case WpsProvisionMethod::DISPLAY:
wps_method = WPS_PIN_DISPLAY;
break;
case WpsProvisionMethod::KEYPAD:
wps_method = WPS_PIN_KEYPAD;
break;
}
int he = wpa_s->conf->p2p_go_he;
int vht = wpa_s->conf->p2p_go_vht;
int ht40 = wpa_s->conf->p2p_go_ht40 || vht;
const char* pin =
pre_selected_pin.length() > 0 ? pre_selected_pin.data() : nullptr;
int new_pin = wpas_p2p_connect(
wpa_s, peer_address.data(), pin, wps_method, persistent, false,
join_existing_group, false, go_intent_signed, 0, 0, -1, false, ht40,
vht, CHANWIDTH_USE_HT, he, 0, nullptr, 0);
if (new_pin < 0) {
return {{SupplicantStatusCode::FAILURE_UNKNOWN, ""}, {}};
}
std::string pin_ret;
if (provision_method == WpsProvisionMethod::DISPLAY &&
pre_selected_pin.empty()) {
pin_ret = misc_utils::convertWpsPinToString(new_pin);
}
return {{SupplicantStatusCode::SUCCESS, ""}, pin_ret};
}
SupplicantStatus P2pIface::cancelConnectInternal()
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
if (wpa_s->scan_res_handler == scanResJoinWrapper) {
wpa_printf(MSG_DEBUG, "P2P: Stop pending group scan for canceling connect");
pending_scan_res_join_callback = NULL;
wpa_s->scan_res_handler = scanResJoinIgnore;
}
if (wpas_p2p_cancel(wpa_s)) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::provisionDiscoveryInternal(
const std::array<uint8_t, 6>& peer_address,
ISupplicantP2pIface::WpsProvisionMethod provision_method)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
p2ps_provision* prov_param;
const char* config_method_str = nullptr;
switch (provision_method) {
case WpsProvisionMethod::PBC:
config_method_str = kConfigMethodStrPbc;
break;
case WpsProvisionMethod::DISPLAY:
config_method_str = kConfigMethodStrDisplay;
break;
case WpsProvisionMethod::KEYPAD:
config_method_str = kConfigMethodStrKeypad;
break;
}
if (wpas_p2p_prov_disc(
wpa_s, peer_address.data(), config_method_str,
WPAS_P2P_PD_FOR_GO_NEG, nullptr)) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::addGroupInternal(
bool persistent, SupplicantNetworkId persistent_network_id)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
int he = wpa_s->conf->p2p_go_he;
int vht = wpa_s->conf->p2p_go_vht;
int ht40 = wpa_s->conf->p2p_go_ht40 || vht;
struct wpa_ssid* ssid =
wpa_config_get_network(wpa_s->conf, persistent_network_id);
if (ssid == NULL) {
if (wpas_p2p_group_add(
wpa_s, persistent, 0, 0, ht40, vht,
CHANWIDTH_USE_HT, he, 0)) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
} else {
return {SupplicantStatusCode::SUCCESS, ""};
}
} else if (ssid->disabled == 2) {
if (wpas_p2p_group_add_persistent(
wpa_s, ssid, 0, 0, 0, 0, ht40, vht,
CHANWIDTH_USE_HT, he, 0, NULL, 0, 0)) {
return {SupplicantStatusCode::FAILURE_NETWORK_UNKNOWN,
""};
} else {
return {SupplicantStatusCode::SUCCESS, ""};
}
}
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
SupplicantStatus P2pIface::removeGroupInternal(const std::string& group_ifname)
{
struct wpa_supplicant* wpa_group_s =
retrieveGroupIfacePtr(group_ifname);
if (!wpa_group_s) {
return {SupplicantStatusCode::FAILURE_IFACE_UNKNOWN, ""};
}
if (wpas_p2p_group_remove(wpa_group_s, group_ifname.c_str())) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::rejectInternal(
const std::array<uint8_t, 6>& peer_address)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
if (wpa_s->global->p2p_disabled || wpa_s->global->p2p == NULL) {
return {SupplicantStatusCode::FAILURE_IFACE_DISABLED, ""};
}
if (wpas_p2p_reject(wpa_s, peer_address.data())) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::inviteInternal(
const std::string& group_ifname,
const std::array<uint8_t, 6>& go_device_address,
const std::array<uint8_t, 6>& peer_address)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
if (wpas_p2p_invite_group(
wpa_s, group_ifname.c_str(), peer_address.data(),
go_device_address.data())) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::reinvokeInternal(
SupplicantNetworkId persistent_network_id,
const std::array<uint8_t, 6>& peer_address)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
int he = wpa_s->conf->p2p_go_he;
int vht = wpa_s->conf->p2p_go_vht;
int ht40 = wpa_s->conf->p2p_go_ht40 || vht;
struct wpa_ssid* ssid =
wpa_config_get_network(wpa_s->conf, persistent_network_id);
if (ssid == NULL || ssid->disabled != 2) {
return {SupplicantStatusCode::FAILURE_NETWORK_UNKNOWN, ""};
}
if (wpas_p2p_invite(
wpa_s, peer_address.data(), ssid, NULL, 0, 0, ht40, vht,
CHANWIDTH_USE_HT, 0, he, 0)) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::configureExtListenInternal(
uint32_t period_in_millis, uint32_t interval_in_millis)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
if (wpas_p2p_ext_listen(wpa_s, period_in_millis, interval_in_millis)) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::setListenChannelInternal(
uint32_t channel, uint32_t operating_class)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
if (p2p_set_listen_channel(
wpa_s->global->p2p, operating_class, channel, 1)) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::setDisallowedFrequenciesInternal(
const std::vector<FreqRange>& ranges)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
using DestT = struct wpa_freq_range_list::wpa_freq_range;
DestT* freq_ranges = nullptr;
// Empty ranges is used to enable all frequencies.
if (ranges.size() != 0) {
freq_ranges = static_cast<DestT*>(
os_malloc(sizeof(DestT) * ranges.size()));
if (!freq_ranges) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
uint32_t i = 0;
for (const auto& range : ranges) {
freq_ranges[i].min = range.min;
freq_ranges[i].max = range.max;
i++;
}
}
os_free(wpa_s->global->p2p_disallow_freq.range);
wpa_s->global->p2p_disallow_freq.range = freq_ranges;
wpa_s->global->p2p_disallow_freq.num = ranges.size();
wpas_p2p_update_channel_list(wpa_s, WPAS_P2P_CHANNEL_UPDATE_DISALLOW);
return {SupplicantStatusCode::SUCCESS, ""};
}
std::pair<SupplicantStatus, std::vector<uint8_t>> P2pIface::getSsidInternal(
const std::array<uint8_t, 6>& peer_address)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
const struct p2p_peer_info* info =
p2p_get_peer_info(wpa_s->global->p2p, peer_address.data(), 0);
if (!info) {
return {{SupplicantStatusCode::FAILURE_UNKNOWN, ""}, {}};
}
const struct p2p_device* dev =
reinterpret_cast<const struct p2p_device*>(
(reinterpret_cast<const uint8_t*>(info)) -
offsetof(struct p2p_device, info));
std::vector<uint8_t> ssid;
if (dev && dev->oper_ssid_len) {
ssid.assign(
dev->oper_ssid, dev->oper_ssid + dev->oper_ssid_len);
}
return {{SupplicantStatusCode::SUCCESS, ""}, ssid};
}
std::pair<SupplicantStatus, uint32_t> P2pIface::getGroupCapabilityInternal(
const std::array<uint8_t, 6>& peer_address)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
const struct p2p_peer_info* info =
p2p_get_peer_info(wpa_s->global->p2p, peer_address.data(), 0);
if (!info) {
return {{SupplicantStatusCode::FAILURE_UNKNOWN, ""}, {}};
}
return {{SupplicantStatusCode::SUCCESS, ""}, info->group_capab};
}
SupplicantStatus P2pIface::addBonjourServiceInternal(
const std::vector<uint8_t>& query, const std::vector<uint8_t>& response)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
auto query_buf = misc_utils::convertVectorToWpaBuf(query);
auto response_buf = misc_utils::convertVectorToWpaBuf(response);
if (!query_buf || !response_buf) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
if (wpas_p2p_service_add_bonjour(
wpa_s, query_buf.get(), response_buf.get())) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
// If successful, the wpabuf is referenced internally and hence should
// not be freed.
query_buf.release();
response_buf.release();
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::removeBonjourServiceInternal(
const std::vector<uint8_t>& query)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
auto query_buf = misc_utils::convertVectorToWpaBuf(query);
if (!query_buf) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
if (wpas_p2p_service_del_bonjour(wpa_s, query_buf.get())) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::addUpnpServiceInternal(
uint32_t version, const std::string& service_name)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
if (wpas_p2p_service_add_upnp(wpa_s, version, service_name.c_str())) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::removeUpnpServiceInternal(
uint32_t version, const std::string& service_name)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
if (wpas_p2p_service_del_upnp(wpa_s, version, service_name.c_str())) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::flushServicesInternal()
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
wpas_p2p_service_flush(wpa_s);
return {SupplicantStatusCode::SUCCESS, ""};
}
std::pair<SupplicantStatus, uint64_t> P2pIface::requestServiceDiscoveryInternal(
const std::array<uint8_t, 6>& peer_address,
const std::vector<uint8_t>& query)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
auto query_buf = misc_utils::convertVectorToWpaBuf(query);
if (!query_buf) {
return {{SupplicantStatusCode::FAILURE_UNKNOWN, ""}, {}};
}
const uint8_t* dst_addr = is_zero_ether_addr(peer_address.data())
? nullptr
: peer_address.data();
uint64_t identifier =
wpas_p2p_sd_request(wpa_s, dst_addr, query_buf.get());
if (identifier == 0) {
return {{SupplicantStatusCode::FAILURE_UNKNOWN, ""}, {}};
}
return {{SupplicantStatusCode::SUCCESS, ""}, identifier};
}
SupplicantStatus P2pIface::cancelServiceDiscoveryInternal(uint64_t identifier)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
if (wpas_p2p_sd_cancel_request(wpa_s, identifier)) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::setMiracastModeInternal(
ISupplicantP2pIface::MiracastMode mode)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
uint8_t mode_internal = convertHidlMiracastModeToInternal(mode);
const std::string cmd_str =
kSetMiracastMode + std::to_string(mode_internal);
std::vector<char> cmd(
cmd_str.c_str(), cmd_str.c_str() + cmd_str.size() + 1);
char driver_cmd_reply_buf[4096] = {};
if (wpa_drv_driver_cmd(
wpa_s, cmd.data(), driver_cmd_reply_buf,
sizeof(driver_cmd_reply_buf))) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::startWpsPbcInternal(
const std::string& group_ifname, const std::array<uint8_t, 6>& bssid)
{
struct wpa_supplicant* wpa_group_s =
retrieveGroupIfacePtr(group_ifname);
if (!wpa_group_s) {
return {SupplicantStatusCode::FAILURE_IFACE_UNKNOWN, ""};
}
const uint8_t* bssid_addr =
is_zero_ether_addr(bssid.data()) ? nullptr : bssid.data();
#ifdef CONFIG_AP
if (wpa_group_s->ap_iface) {
if (wpa_supplicant_ap_wps_pbc(wpa_group_s, bssid_addr, NULL)) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
#endif /* CONFIG_AP */
if (wpas_wps_start_pbc(wpa_group_s, bssid_addr, 0, 0)) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::startWpsPinKeypadInternal(
const std::string& group_ifname, const std::string& pin)
{
struct wpa_supplicant* wpa_group_s =
retrieveGroupIfacePtr(group_ifname);
if (!wpa_group_s) {
return {SupplicantStatusCode::FAILURE_IFACE_UNKNOWN, ""};
}
#ifdef CONFIG_AP
if (wpa_group_s->ap_iface) {
if (wpa_supplicant_ap_wps_pin(
wpa_group_s, nullptr, pin.c_str(), nullptr, 0, 0) < 0) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
#endif /* CONFIG_AP */
if (wpas_wps_start_pin(
wpa_group_s, nullptr, pin.c_str(), 0, DEV_PW_DEFAULT)) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
std::pair<SupplicantStatus, std::string> P2pIface::startWpsPinDisplayInternal(
const std::string& group_ifname, const std::array<uint8_t, 6>& bssid)
{
struct wpa_supplicant* wpa_group_s =
retrieveGroupIfacePtr(group_ifname);
if (!wpa_group_s) {
return {{SupplicantStatusCode::FAILURE_IFACE_UNKNOWN, ""}, ""};
}
const uint8_t* bssid_addr =
is_zero_ether_addr(bssid.data()) ? nullptr : bssid.data();
int pin = wpas_wps_start_pin(
wpa_group_s, bssid_addr, nullptr, 0, DEV_PW_DEFAULT);
if (pin < 0) {
return {{SupplicantStatusCode::FAILURE_UNKNOWN, ""}, ""};
}
return {{SupplicantStatusCode::SUCCESS, ""},
misc_utils::convertWpsPinToString(pin)};
}
SupplicantStatus P2pIface::cancelWpsInternal(const std::string& group_ifname)
{
struct wpa_supplicant* wpa_group_s =
retrieveGroupIfacePtr(group_ifname);
if (!wpa_group_s) {
return {SupplicantStatusCode::FAILURE_IFACE_UNKNOWN, ""};
}
if (wpas_wps_cancel(wpa_group_s)) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::setWpsDeviceNameInternal(const std::string& name)
{
return iface_config_utils::setWpsDeviceName(retrieveIfacePtr(), name);
}
SupplicantStatus P2pIface::setWpsDeviceTypeInternal(
const std::array<uint8_t, 8>& type)
{
return iface_config_utils::setWpsDeviceType(retrieveIfacePtr(), type);
}
SupplicantStatus P2pIface::setWpsManufacturerInternal(
const std::string& manufacturer)
{
return iface_config_utils::setWpsManufacturer(
retrieveIfacePtr(), manufacturer);
}
SupplicantStatus P2pIface::setWpsModelNameInternal(
const std::string& model_name)
{
return iface_config_utils::setWpsModelName(
retrieveIfacePtr(), model_name);
}
SupplicantStatus P2pIface::setWpsModelNumberInternal(
const std::string& model_number)
{
return iface_config_utils::setWpsModelNumber(
retrieveIfacePtr(), model_number);
}
SupplicantStatus P2pIface::setWpsSerialNumberInternal(
const std::string& serial_number)
{
return iface_config_utils::setWpsSerialNumber(
retrieveIfacePtr(), serial_number);
}
SupplicantStatus P2pIface::setWpsConfigMethodsInternal(uint16_t config_methods)
{
return iface_config_utils::setWpsConfigMethods(
retrieveIfacePtr(), config_methods);
}
SupplicantStatus P2pIface::enableWfdInternal(bool enable)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
wifi_display_enable(wpa_s->global, enable);
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::setWfdDeviceInfoInternal(
const std::array<uint8_t, 6>& info)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
std::vector<char> wfd_device_info_hex(info.size() * 2 + 1);
wpa_snprintf_hex(
wfd_device_info_hex.data(), wfd_device_info_hex.size(), info.data(),
info.size());
// |wifi_display_subelem_set| expects the first 2 bytes
// to hold the lenght of the subelement. In this case it's
// fixed to 6, so prepend that.
std::string wfd_device_info_set_cmd_str =
std::to_string(kWfdDeviceInfoSubelemId) + " " +
kWfdDeviceInfoSubelemLenHexStr + wfd_device_info_hex.data();
std::vector<char> wfd_device_info_set_cmd(
wfd_device_info_set_cmd_str.c_str(),
wfd_device_info_set_cmd_str.c_str() +
wfd_device_info_set_cmd_str.size() + 1);
if (wifi_display_subelem_set(
wpa_s->global, wfd_device_info_set_cmd.data())) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
std::pair<SupplicantStatus, std::vector<uint8_t>>
P2pIface::createNfcHandoverRequestMessageInternal()
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
auto buf = misc_utils::createWpaBufUniquePtr(
wpas_p2p_nfc_handover_req(wpa_s, 1));
if (!buf) {
return {{SupplicantStatusCode::FAILURE_UNKNOWN, ""}, {}};
}
return {{SupplicantStatusCode::SUCCESS, ""},
misc_utils::convertWpaBufToVector(buf.get())};
}
std::pair<SupplicantStatus, std::vector<uint8_t>>
P2pIface::createNfcHandoverSelectMessageInternal()
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
auto buf = misc_utils::createWpaBufUniquePtr(
wpas_p2p_nfc_handover_sel(wpa_s, 1, 0));
if (!buf) {
return {{SupplicantStatusCode::FAILURE_UNKNOWN, ""}, {}};
}
return {{SupplicantStatusCode::SUCCESS, ""},
misc_utils::convertWpaBufToVector(buf.get())};
}
SupplicantStatus P2pIface::reportNfcHandoverResponseInternal(
const std::vector<uint8_t>& request)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
auto req = misc_utils::convertVectorToWpaBuf(request);
auto sel = misc_utils::convertVectorToWpaBuf(std::vector<uint8_t>{0});
if (!req || !sel) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
if (wpas_p2p_nfc_report_handover(wpa_s, 0, req.get(), sel.get(), 0)) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::reportNfcHandoverInitiationInternal(
const std::vector<uint8_t>& select)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
auto req = misc_utils::convertVectorToWpaBuf(std::vector<uint8_t>{0});
auto sel = misc_utils::convertVectorToWpaBuf(select);
if (!req || !sel) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
if (wpas_p2p_nfc_report_handover(wpa_s, 1, req.get(), sel.get(), 0)) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::saveConfigInternal()
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
if (!wpa_s->conf->update_config) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
if (wpa_config_write(wpa_s->confname, wpa_s->conf)) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::addGroup_1_2Internal(
const std::vector<uint8_t>& ssid, const std::string& passphrase,
bool persistent, uint32_t freq, const std::array<uint8_t, 6>& peer_address,
bool joinExistingGroup)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
int he = wpa_s->conf->p2p_go_he;
int vht = wpa_s->conf->p2p_go_vht;
int ht40 = wpa_s->conf->p2p_go_ht40 || vht;
if (wpa_s->global->p2p == NULL || wpa_s->global->p2p_disabled) {
return {SupplicantStatusCode::FAILURE_IFACE_DISABLED, ""};
}
if (!isSsidValid(ssid)) {
return {SupplicantStatusCode::FAILURE_ARGS_INVALID, "SSID is invalid."};
}
if (!isPskPassphraseValid(passphrase)) {
return {SupplicantStatusCode::FAILURE_ARGS_INVALID, "passphrase is invalid."};
}
if (!joinExistingGroup) {
struct p2p_data *p2p = wpa_s->global->p2p;
os_memcpy(p2p->ssid, ssid.data(), ssid.size());
p2p->ssid_len = ssid.size();
p2p->ssid_set = 1;
os_memset(p2p->passphrase, 0, sizeof(p2p->passphrase));
os_memcpy(p2p->passphrase, passphrase.c_str(), passphrase.length());
p2p->passphrase_set = 1;
if (wpas_p2p_group_add(
wpa_s, persistent, freq, 0, ht40, vht,
CHANWIDTH_USE_HT, he, 0)) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, ""};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
// The rest is for group join.
wpa_printf(MSG_DEBUG, "P2P: Stop any on-going P2P FIND before group join.");
wpas_p2p_stop_find(wpa_s);
struct wpa_bss *bss = findBssBySsid(
wpa_s, peer_address.data(),
ssid.data(), ssid.size());
if (bss != NULL) {
wpa_printf(MSG_DEBUG, "P2P: Join group with Group Owner " MACSTR,
MAC2STR(bss->bssid));
if (0 != joinGroup(wpa_s, bss->bssid, ssid, passphrase)) {
// no need to notify group join failure here,
// it will be handled by wpas_p2p_group_add_persistent
// called in joinGroup.
return {SupplicantStatusCode::FAILURE_UNKNOWN, "Failed to join a group."};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
wpa_printf(MSG_INFO, "No matched BSS exists, try to find it by scan");
if (pending_scan_res_join_callback != NULL) {
wpa_printf(MSG_WARNING, "P2P: Renew scan result callback with new request.");
}
pending_join_scan_callback =
[wpa_s, ssid, freq]() {
if (wpa_s->global->p2p == NULL || wpa_s->global->p2p_disabled) {
return;
}
int ret = joinScanReq(wpa_s, ssid, freq);
// for BUSY case, the scan might be occupied by WiFi.
// Do not give up immediately, but try again later.
if (-EBUSY == ret) {
// re-schedule this join scan and don't consume retry count.
if (pending_scan_res_join_callback) {
wpa_s->p2p_join_scan_count--;
pending_scan_res_join_callback();
}
} else if (0 != ret) {
notifyGroupJoinFailure(wpa_s);
pending_scan_res_join_callback = NULL;
}
};
pending_scan_res_join_callback = [wpa_s, ssid, passphrase, peer_address, this]() {
if (wpa_s->global->p2p == NULL || wpa_s->global->p2p_disabled) {
return;
}
wpa_printf(MSG_DEBUG, "P2P: Scan results received for join (reinvoke).");
struct wpa_bss *bss = findBssBySsid(
wpa_s, peer_address.data(), ssid.data(), ssid.size());
if (bss) {
if (0 != joinGroup(wpa_s, bss->bssid, ssid, passphrase)) {
wpa_printf(MSG_ERROR, "P2P: Failed to join a group.");
}
// no need to notify group join failure here,
// it will be handled by wpas_p2p_group_add_persistent
// called in joinGroup.
pending_scan_res_join_callback = NULL;
return;
}
wpa_s->p2p_join_scan_count++;
wpa_printf(MSG_DEBUG, "P2P: Join scan attempt %d.", wpa_s->p2p_join_scan_count);
eloop_cancel_timeout(joinScanWrapper, wpa_s, NULL);
if (wpa_s->p2p_join_scan_count <= P2P_MAX_JOIN_SCAN_ATTEMPTS) {
wpa_printf(MSG_DEBUG, "P2P: Try join again later.");
eloop_register_timeout(1, 0, joinScanWrapper, wpa_s, this);
return;
}
wpa_printf(MSG_ERROR, "P2P: Failed to find the group with "
"network name %s - stop join attempt",
ssid.data());
notifyGroupJoinFailure(wpa_s);
pending_scan_res_join_callback = NULL;
};
wpa_s->p2p_join_scan_count = 0;
pending_join_scan_callback();
if (pending_scan_res_join_callback == NULL) {
return {SupplicantStatusCode::FAILURE_UNKNOWN, "Failed to start scan."};
}
return {SupplicantStatusCode::SUCCESS, ""};
}
SupplicantStatus P2pIface::setMacRandomizationInternal(bool enable)
{
struct wpa_supplicant* wpa_s = retrieveIfacePtr();
bool currentEnabledState = !!wpa_s->conf->p2p_device_random_mac_addr;
u8 *addr = NULL;
// A dedicated p2p device is not managed by supplicant,
// supplicant could not change its MAC address.
if (wpa_s->drv_flags & WPA_DRIVER_FLAGS_DEDICATED_P2P_DEVICE) {
wpa_printf(MSG_ERROR,
"Dedicated P2P device don't support MAC randomization");
return {SupplicantStatusCode::FAILURE_ARGS_INVALID, "NotSupported"};
}
// The same state, no change is needed.
if (currentEnabledState == enable) {
wpa_printf(MSG_DEBUG, "The random MAC is %s already.",
(enable) ? "enabled" : "disabled");
return {SupplicantStatusCode::SUCCESS, ""};
}
if (enable) {
wpa_s->conf->p2p_device_random_mac_addr = 1;
wpa_s->conf->p2p_interface_random_mac_addr = 1;
// restore config if it failed to set up MAC address.
if (wpas_p2p_mac_setup(wpa_s) < 0) {
wpa_s->conf->p2p_device_random_mac_addr = 0;
wpa_s->conf->p2p_interface_random_mac_addr = 0;
return {SupplicantStatusCode::FAILURE_UNKNOWN,
"Failed to set up MAC address."};
}
} else {
// disable random MAC will use original MAC address
// regardless of any saved persistent groups.
if (wpa_drv_set_mac_addr(wpa_s, NULL) < 0) {
wpa_printf(MSG_ERROR, "Failed to restore MAC address");
return {SupplicantStatusCode::FAILURE_UNKNOWN,
"Failed to restore MAC address."};
}
if (wpa_supplicant_update_mac_addr(wpa_s) < 0) {
wpa_printf(MSG_INFO, "Could not update MAC address information");
return {SupplicantStatusCode::FAILURE_UNKNOWN,
"Failed to update MAC address."};
}
wpa_s->conf->p2p_device_random_mac_addr = 0;
wpa_s->conf->p2p_interface_random_mac_addr = 0;
}
// update internal data to send out correct device address in action frame.
os_memcpy(wpa_s->global->p2p_dev_addr, wpa_s->own_addr, ETH_ALEN);
os_memcpy(wpa_s->global->p2p->cfg->dev_addr, wpa_s->global->p2p_dev_addr, ETH_ALEN);
return {SupplicantStatusCode::SUCCESS, ""};
}
/**
* Retrieve the underlying |wpa_supplicant| struct
* pointer for this iface.
* If the underlying iface is removed, then all RPC method calls on this object
* will return failure.
*/
wpa_supplicant* P2pIface::retrieveIfacePtr()
{
return wpa_supplicant_get_iface(wpa_global_, ifname_.c_str());
}
/**
* Retrieve the underlying |wpa_supplicant| struct
* pointer for this group iface.
*/
wpa_supplicant* P2pIface::retrieveGroupIfacePtr(const std::string& group_ifname)
{
return wpa_supplicant_get_iface(wpa_global_, group_ifname.c_str());
}
} // namespace implementation
} // namespace V1_3
} // namespace supplicant
} // namespace wifi
} // namespace hardware
} // namespace android
|
dnl Pentium-4 mpn_copyi -- copy limb vector, incrementing.
dnl Copyright 1999-2001 Free Software Foundation, Inc.
dnl This file is part of the GNU MP Library.
dnl
dnl The GNU MP Library is free software; you can redistribute it and/or modify
dnl it under the terms of either:
dnl
dnl * the GNU Lesser General Public License as published by the Free
dnl Software Foundation; either version 3 of the License, or (at your
dnl option) any later version.
dnl
dnl or
dnl
dnl * the GNU General Public License as published by the Free Software
dnl Foundation; either version 2 of the License, or (at your option) any
dnl later version.
dnl
dnl or both in parallel, as here.
dnl
dnl The GNU MP Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
dnl for more details.
dnl
dnl You should have received copies of the GNU General Public License and the
dnl GNU Lesser General Public License along with the GNU MP Library. If not,
dnl see https://www.gnu.org/licenses/.
dnl The rep/movsl is very slow for small blocks on pentium4. Its startup
dnl time seems to be about 110 cycles. It then copies at a rate of one
dnl limb per cycle. We therefore fall back to an open-coded 2 c/l copying
dnl loop for smaller sizes.
dnl Ultimately, we may want to use 64-bit movd or 128-bit movdqu in some
dnl nifty unrolled arrangement. Clearly, that could reach much higher
dnl speeds, at least for large blocks.
include(`../config.m4')
defframe(PARAM_SIZE, 12)
defframe(PARAM_SRC, 8)
defframe(PARAM_DST, 4)
TEXT
ALIGN(8)
PROLOGUE(mpn_copyi)
deflit(`FRAME',0)
movl PARAM_SIZE, %ecx
cmpl $150, %ecx
jg L(replmovs)
movl PARAM_SRC, %eax
movl PARAM_DST, %edx
movl %ebx, PARAM_SIZE
testl %ecx, %ecx
jz L(end)
L(loop):
movl (%eax), %ebx
leal 4(%eax), %eax
addl $-1, %ecx
movl %ebx, (%edx)
leal 4(%edx), %edx
jnz L(loop)
L(end):
movl PARAM_SIZE, %ebx
ret
L(replmovs):
cld C better safe than sorry, see mpn/x86/README
movl %esi, %eax
movl PARAM_SRC, %esi
movl %edi, %edx
movl PARAM_DST, %edi
rep
movsl
movl %eax, %esi
movl %edx, %edi
ret
EPILOGUE()
|
.global s_prepare_buffers
s_prepare_buffers:
push %r15
push %rbp
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_A_ht+0x735c, %rsi
lea addresses_WC_ht+0xa170, %rdi
sub $24867, %rbx
mov $47, %rcx
rep movsq
nop
nop
add $45601, %rbp
lea addresses_WC_ht+0x1d018, %rsi
lea addresses_normal_ht+0x10568, %rdi
nop
cmp %r15, %r15
mov $116, %rcx
rep movsw
nop
nop
nop
nop
nop
sub %rcx, %rcx
lea addresses_WC_ht+0x120e0, %rdi
nop
nop
nop
nop
nop
add %rcx, %rcx
mov $0x6162636465666768, %rsi
movq %rsi, %xmm6
vmovups %ymm6, (%rdi)
nop
nop
nop
xor %rcx, %rcx
lea addresses_normal_ht+0x15ae0, %rdi
nop
xor %rdx, %rdx
and $0xffffffffffffffc0, %rdi
vmovaps (%rdi), %ymm4
vextracti128 $1, %ymm4, %xmm4
vpextrq $0, %xmm4, %rbx
nop
xor %rcx, %rcx
lea addresses_WC_ht+0x140b0, %rsi
lea addresses_A_ht+0x4e0, %rdi
nop
nop
nop
add $13999, %rdx
mov $6, %rcx
rep movsl
nop
nop
nop
nop
nop
and $40772, %rbx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r15
ret
.global s_faulty_load
s_faulty_load:
push %r13
push %r14
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
// Store
lea addresses_RW+0x19fc0, %r14
nop
nop
nop
nop
sub %rdi, %rdi
mov $0x5152535455565758, %rdx
movq %rdx, %xmm1
vmovups %ymm1, (%r14)
nop
nop
nop
cmp %r14, %r14
// Store
lea addresses_US+0x1fce0, %rax
nop
nop
inc %rsi
mov $0x5152535455565758, %r14
movq %r14, (%rax)
nop
nop
add %r14, %r14
// Load
lea addresses_D+0x154e0, %r14
nop
nop
nop
nop
add $63693, %r13
mov (%r14), %di
nop
nop
xor $5241, %rax
// Load
lea addresses_WC+0x16c7b, %rsi
nop
nop
sub %r14, %r14
mov (%rsi), %edx
nop
nop
nop
nop
add %r14, %r14
// Faulty Load
lea addresses_WC+0x132e0, %r13
nop
cmp $24674, %rdi
mov (%r13), %eax
lea oracles, %r13
and $0xff, %rax
shlq $12, %rax
mov (%r13,%rax,1), %rax
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r14
pop %r13
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_RW', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 3, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_US', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_D', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'size': 4, 'AVXalign': False, 'NT': True, 'congruent': 0, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 4, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 32, 'AVXalign': True, 'NT': True, 'congruent': 11, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 8, 'same': False}}
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
org #5CCB
basic:
dw #00,endB - startLine
startLine:
db #F9,#C0 ; RANDOMIZE USR
db '23774' ; ADDR
db #3A,#EA ; : REM
db #0E,#00,#00
; ADDR value
dw code
db #00
code: ; 23774
include "includes.asm"
vars:
db #0D
display "Launch address: ",/A,code
display "vars address: ",/A,vars
display "listener: ",/A,CONTROL.digListener
endB:
EMPTYTAP Wow.tap
SAVETAP "Wow.tap", BASIC,"Wow", basic, endB-basic, 0
TAPOUT Wow.tap
TAPEND
include "variables.asm" |
// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.
//
// 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.
#ifndef ROCPRIM_BLOCK_BLOCK_SCAN_HPP_
#define ROCPRIM_BLOCK_BLOCK_SCAN_HPP_
#include <type_traits>
#include "../config.hpp"
#include "../detail/various.hpp"
#include "../intrinsics.hpp"
#include "../functional.hpp"
#include "detail/block_scan_warp_scan.hpp"
#include "detail/block_scan_reduce_then_scan.hpp"
/// \addtogroup blockmodule
/// @{
BEGIN_ROCPRIM_NAMESPACE
/// \brief Available algorithms for block_scan primitive.
enum class block_scan_algorithm
{
/// \brief A warp_scan based algorithm.
using_warp_scan,
/// \brief An algorithm which limits calculations to a single hardware warp.
reduce_then_scan,
/// \brief Default block_scan algorithm.
default_algorithm = using_warp_scan,
};
namespace detail
{
// Selector for block_scan algorithm which gives block scan implementation
// type based on passed block_scan_algorithm enum
template<block_scan_algorithm Algorithm>
struct select_block_scan_impl;
template<>
struct select_block_scan_impl<block_scan_algorithm::using_warp_scan>
{
template<class T, unsigned int BlockSize>
using type = block_scan_warp_scan<T, BlockSize>;
};
template<>
struct select_block_scan_impl<block_scan_algorithm::reduce_then_scan>
{
template<class T, unsigned int BlockSize>
// When BlockSize is less than hardware warp size block_scan_warp_scan performs better than
// block_scan_reduce_then_scan by specializing for warps
using type = typename std::conditional<
(BlockSize <= ::rocprim::warp_size()),
block_scan_warp_scan<T, BlockSize>,
block_scan_reduce_then_scan<T, BlockSize>
>::type;
};
} // end namespace detail
/// \brief The block_scan class is a block level parallel primitive which provides methods
/// for performing inclusive and exclusive scan operations of items partitioned across
/// threads in a block.
///
/// \tparam T - the input/output type.
/// \tparam BlockSize - the number of threads in a block.
/// \tparam Algorithm - selected scan algorithm, block_scan_algorithm::default_algorithm by default.
///
/// \par Overview
/// * Supports non-commutative scan operators. However, a scan operator should be
/// associative. When used with non-associative functions the results may be non-deterministic
/// and/or vary in precision.
/// * Computation can more efficient when:
/// * \p ItemsPerThread is greater than one,
/// * \p T is an arithmetic type,
/// * scan operation is simple addition operator, and
/// * the number of threads in the block is a multiple of the hardware warp size (see rocprim::warp_size()).
/// * block_scan has two alternative implementations: \p block_scan_algorithm::using_warp_scan
/// and block_scan_algorithm::reduce_then_scan.
///
/// \par Examples
/// \parblock
/// In the examples scan operation is performed on block of 192 threads, each provides
/// one \p int value, result is returned using the same variable as for input.
///
/// \b HIP: \n
/// \code{.cpp}
/// __global__ void example_kernel(...)
/// {
/// // specialize warp_scan for int and logical warp of 192 threads
/// using block_scan_int = rocprim::block_scan<int, 192>;
/// // allocate storage in shared memory
/// __shared__ block_scan_int::storage_type storage;
///
/// int value = ...;
/// // execute inclusive scan
/// block_scan_int().inclusive_scan(
/// value, // input
/// value, // output
/// storage
/// );
/// ...
/// }
/// \endcode
///
/// \b HC: \n
/// \code{.cpp}
/// hc::parallel_for_each(
/// hc::extent<1>(...).tile(64),
/// [=](hc::tiled_index<1> i) [[hc]]
/// {
/// // specialize warp_scan for int and logical warp of 16 threads
/// using block_scan_int = rocprim::block_scan<int, 192>;
///
/// // allocate storage in shared memory
/// tile_static block_scan_int::storage_type storage;///
///
/// int value = ...;
/// // execute inclusive scan
/// block_scan_int().inclusive_scan(
/// value, // input
/// value, // output
/// storage
/// );
/// }
/// );
/// \endcode
/// \endparblock
template<
class T,
unsigned int BlockSize,
block_scan_algorithm Algorithm = block_scan_algorithm::default_algorithm
>
class block_scan
#ifndef DOXYGEN_SHOULD_SKIP_THIS
: private detail::select_block_scan_impl<Algorithm>::template type<T, BlockSize>
#endif
{
using base_type = typename detail::select_block_scan_impl<Algorithm>::template type<T, BlockSize>;
public:
/// \brief Struct used to allocate a temporary memory that is required for thread
/// communication during operations provided by related parallel primitive.
///
/// Depending on the implemention the operations exposed by parallel primitive may
/// require a temporary storage for thread communication. The storage should be allocated
/// using keywords <tt>__shared__</tt> in HIP or \p tile_static in HC. It can be aliased to
/// an externally allocated memory, or be a part of a union type with other storage types
/// to increase shared memory reusability.
using storage_type = typename base_type::storage_type;
/// \brief Performs inclusive scan across threads in a block.
///
/// \tparam BinaryFunction - type of binary function used for scan. Default type
/// is rocprim::plus<T>.
///
/// \param [in] input - thread input value.
/// \param [out] output - reference to a thread output value. May be aliased with \p input.
/// \param [in] storage - reference to a temporary storage object of type storage_type.
/// \param [in] scan_op - binary operation function object that will be used for scan.
/// The signature of the function should be equivalent to the following:
/// <tt>T f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
///
/// \par Storage reusage
/// Synchronization barrier should be placed before \p storage is reused
/// or repurposed: \p __syncthreads() in HIP, \p tile_barrier::wait() in HC, or
/// universal rocprim::syncthreads().
///
/// \par Examples
/// \parblock
/// The examples present inclusive min scan operations performed on a block of 256 threads,
/// each provides one \p float value.
///
/// \b HIP: \n
/// \code{.cpp}
/// __global__ void example_kernel(...) // hipBlockDim_x = 256
/// {
/// // specialize block_scan for float and block of 256 threads
/// using block_scan_f = rocprim::block_scan<float, 256>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_float::storage_type storage;
///
/// float input = ...;
/// float output;
/// // execute inclusive min scan
/// block_scan_float().inclusive_scan(
/// input,
/// output,
/// storage,
/// rocprim::minimum<float>()
/// );
/// ...
/// }
/// \endcode
///
/// \b HC: \n
/// \code{.cpp}
/// hc::parallel_for_each(
/// hc::extent<1>(...).tile(256),
/// [=](hc::tiled_index<1> i) [[hc]]
/// {
/// // specialize block_scan for float and block of 256 threads
/// using block_scan_f = rocprim::block_scan<float, 256>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_float::storage_type storage;
///
/// float input = ...;
/// float output;
/// // execute inclusive min scan
/// block_scan_float().inclusive_scan(
/// input,
/// output,
/// storage,
/// rocprim::minimum<float>()
/// );
/// ...
/// }
/// );
/// \endcode
/// If the \p input values across threads in a block are <tt>{1, -2, 3, -4, ..., 255, -256}</tt>, then
/// \p output values in will be <tt>{1, -2, -2, -4, ..., -254, -256}</tt>.
/// \endparblock
template<class BinaryFunction = ::rocprim::plus<T>>
ROCPRIM_DEVICE inline
void inclusive_scan(T input,
T& output,
storage_type& storage,
BinaryFunction scan_op = BinaryFunction())
{
base_type::inclusive_scan(input, output, storage, scan_op);
}
/// \overload
/// \brief Performs inclusive scan across threads in a block.
///
/// * This overload does not accept storage argument. Required shared memory is
/// allocated by the method itself.
///
/// \tparam BinaryFunction - type of binary function used for scan. Default type
/// is rocprim::plus<T>.
///
/// \param [in] input - thread input value.
/// \param [out] output - reference to a thread output value. May be aliased with \p input.
/// \param [in] scan_op - binary operation function object that will be used for scan.
/// The signature of the function should be equivalent to the following:
/// <tt>T f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
template<class BinaryFunction = ::rocprim::plus<T>>
ROCPRIM_DEVICE inline
void inclusive_scan(T input,
T& output,
BinaryFunction scan_op = BinaryFunction())
{
base_type::inclusive_scan(input, output, scan_op);
}
/// \brief Performs inclusive scan and reduction across threads in a block.
///
/// \tparam BinaryFunction - type of binary function used for scan. Default type
/// is rocprim::plus<T>.
///
/// \param [in] input - thread input value.
/// \param [out] output - reference to a thread output value. May be aliased with \p input.
/// \param [out] reduction - result of reducing of all \p input values in a block.
/// \param [in] storage - reference to a temporary storage object of type storage_type.
/// \param [in] scan_op - binary operation function object that will be used for scan.
/// The signature of the function should be equivalent to the following:
/// <tt>T f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
///
/// \par Storage reusage
/// Synchronization barrier should be placed before \p storage is reused
/// or repurposed: \p __syncthreads() in HIP, \p tile_barrier::wait() in HC, or
/// universal rocprim::syncthreads().
///
/// \par Examples
/// \parblock
/// The examples present inclusive min scan operations performed on a block of 256 threads,
/// each provides one \p float value.
///
/// \b HIP: \n
/// \code{.cpp}
/// __global__ void example_kernel(...) // hipBlockDim_x = 256
/// {
/// // specialize block_scan for float and block of 256 threads
/// using block_scan_f = rocprim::block_scan<float, 256>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_float::storage_type storage;
///
/// float input = ...;
/// float output;
/// float reduction;
/// // execute inclusive min scan
/// block_scan_float().inclusive_scan(
/// input,
/// output,
/// reduction,
/// storage,
/// rocprim::minimum<float>()
/// );
/// ...
/// }
/// \endcode
///
/// \b HC: \n
/// \code{.cpp}
/// hc::parallel_for_each(
/// hc::extent<1>(...).tile(256),
/// [=](hc::tiled_index<1> i) [[hc]]
/// {
/// // specialize block_scan for float and block of 256 threads
/// using block_scan_f = rocprim::block_scan<float, 256>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_float::storage_type storage;
///
/// float input = ...;
/// float output;
/// float reduction;
/// // execute inclusive min scan
/// block_scan_float().inclusive_scan(
/// input,
/// output,
/// reduction,
/// storage,
/// rocprim::minimum<float>()
/// );
/// ...
/// }
/// );
/// \endcode
/// If the \p input values across threads in a block are <tt>{1, -2, 3, -4, ..., 255, -256}</tt>, then
/// \p output values in will be <tt>{1, -2, -2, -4, ..., -254, -256}</tt>, and the \p reduction will
/// be <tt>-256</tt>.
/// \endparblock
template<class BinaryFunction = ::rocprim::plus<T>>
ROCPRIM_DEVICE inline
void inclusive_scan(T input,
T& output,
T& reduction,
storage_type& storage,
BinaryFunction scan_op = BinaryFunction())
{
base_type::inclusive_scan(input, output, reduction, storage, scan_op);
}
/// \overload
/// \brief Performs inclusive scan and reduction across threads in a block.
///
/// * This overload does not accept storage argument. Required shared memory is
/// allocated by the method itself.
///
/// \tparam BinaryFunction - type of binary function used for scan. Default type
/// is rocprim::plus<T>.
///
/// \param [in] input - thread input value.
/// \param [out] output - reference to a thread output value. May be aliased with \p input.
/// \param [out] reduction - result of reducing of all \p input values in a block.
/// \param [in] scan_op - binary operation function object that will be used for scan.
/// The signature of the function should be equivalent to the following:
/// <tt>T f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
template<class BinaryFunction = ::rocprim::plus<T>>
ROCPRIM_DEVICE inline
void inclusive_scan(T input,
T& output,
T& reduction,
BinaryFunction scan_op = BinaryFunction())
{
base_type::inclusive_scan(input, output, reduction, scan_op);
}
/// \brief Performs inclusive scan across threads in a block, and uses
/// \p prefix_callback_op to generate prefix value for the whole block.
///
/// \tparam PrefixCallback - type of the unary function object used for generating
/// block-wide prefix value for the scan operation.
/// \tparam BinaryFunction - type of binary function used for scan. Default type
/// is rocprim::plus<T>.
///
/// \param [in] input - thread input value.
/// \param [out] output - reference to a thread output value. May be aliased with \p input.
/// \param [in] storage - reference to a temporary storage object of type storage_type.
/// \param [in,out] prefix_callback_op - function object for generating block prefix value.
/// The signature of the \p prefix_callback_op should be equivalent to the following:
/// <tt>T f(const T &block_reduction);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
/// The object will be called by the first thread in the first warp from the block with
/// block reduction of \p input values as input argument. The result will be used as the
/// block-wide prefix.
/// \param [in] scan_op - binary operation function object that will be used for scan.
/// The signature of the function should be equivalent to the following:
/// <tt>T f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
///
/// \par Storage reusage
/// Synchronization barrier should be placed before \p storage is reused
/// or repurposed: \p __syncthreads() in HIP, \p tile_barrier::wait() in HC, or
/// universal rocprim::syncthreads().
///
/// \par Examples
/// \parblock
/// The examples present inclusive prefix sum operations performed on a block of 256 threads,
/// each thread provides one \p int value.
///
/// \b HIP: \n
/// \code{.cpp}
///
/// struct my_block_prefix
/// {
/// int prefix;
///
/// __device__ my_block_prefix(int prefix) : prefix(prefix) {}
///
/// __device__ int operator()(int block_reduction)
/// {
/// int old_prefix = prefix;
/// prefix = prefix + block_reduction;
/// return old_prefix;
/// }
/// };
///
/// __global__ void example_kernel(...) // hipBlockDim_x = 256
/// {
/// // specialize block_scan for int and block of 256 threads
/// using block_scan_f = rocprim::block_scan<int, 256>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_int::storage_type storage;
///
/// // init prefix functor
/// my_block_prefix prefix_callback(10);
///
/// int input;
/// int output;
/// // execute inclusive prefix sum
/// block_scan_int().inclusive_scan(
/// input,
/// output,
/// storage,
/// prefix_callback,
/// rocprim::plus<int>()
/// );
/// ...
/// }
/// \endcode
///
/// \b HC: \n
/// \code{.cpp}
/// hc::parallel_for_each(
/// hc::extent<1>(...).tile(256),
/// [=](hc::tiled_index<1> i) [[hc]]
/// {
/// // specialize block_scan for int and block of 256 threads
/// using block_scan_f = rocprim::block_scan<int, 256>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_int::storage_type storage;
///
/// int prefix = 10;
/// auto prefix_callback = [&prefix](int reduction)
/// {
/// int old_prefix = prefix;
/// prefix += reduction;
/// return old_prefix;
/// };
///
/// int input = ...;
/// int output;
/// // execute inclusive min scan
/// block_scan_int().inclusive_scan(
/// input,
/// output,
/// storage,
/// prefix_callback,
/// rocprim::plus<int>()
/// );
/// ...
/// }
/// );
/// \endcode
/// If the \p input values across threads in a block are <tt>{1, 1, 1, ..., 1}</tt>, then
/// \p output values in will be <tt>{11, 12, 13, ..., 266}</tt>, and the \p prefix will
/// be <tt>266</tt>.
/// \endparblock
template<
class PrefixCallback,
class BinaryFunction = ::rocprim::plus<T>
>
ROCPRIM_DEVICE inline
void inclusive_scan(T input,
T& output,
storage_type& storage,
PrefixCallback& prefix_callback_op,
BinaryFunction scan_op)
{
base_type::inclusive_scan(input, output, storage, prefix_callback_op, scan_op);
}
/// \brief Performs inclusive scan across threads in a block.
///
/// \tparam ItemsPerThread - number of items in the \p input array.
/// \tparam BinaryFunction - type of binary function used for scan. Default type
/// is rocprim::plus<T>.
///
/// \param [in] input - reference to an array containing thread input values.
/// \param [out] output - reference to a thread output array. May be aliased with \p input.
/// \param [in] storage - reference to a temporary storage object of type storage_type.
/// \param [in] scan_op - binary operation function object that will be used for scan.
/// The signature of the function should be equivalent to the following:
/// <tt>T f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
///
/// \par Storage reusage
/// Synchronization barrier should be placed before \p storage is reused
/// or repurposed: \p __syncthreads() in HIP, \p tile_barrier::wait() in HC, or
/// universal rocprim::syncthreads().
///
/// \par Examples
/// \parblock
/// The examples present inclusive maximum scan operations performed on a block of 128 threads,
/// each provides two \p long value.
///
/// \b HIP: \n
/// \code{.cpp}
/// __global__ void example_kernel(...) // hipBlockDim_x = 128
/// {
/// // specialize block_scan for long and block of 128 threads
/// using block_scan_f = rocprim::block_scan<long, 128>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_long::storage_type storage;
///
/// long input[2] = ...;
/// long output[2];
/// // execute inclusive min scan
/// block_scan_long().inclusive_scan(
/// input,
/// output,
/// storage,
/// rocprim::maximum<long>()
/// );
/// ...
/// }
/// \endcode
///
/// \b HC: \n
/// \code{.cpp}
/// hc::parallel_for_each(
/// hc::extent<1>(...).tile(128),
/// [=](hc::tiled_index<1> i) [[hc]]
/// {
/// // specialize block_scan for long and block of 128 threads
/// using block_scan_f = rocprim::block_scan<long, 128>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_long::storage_type storage;
///
/// long input[2] = ...;
/// long output[2];
/// // execute inclusive min scan
/// block_scan_long().inclusive_scan(
/// input,
/// output,
/// storage,
/// rocprim::maximum<long>()
/// );
/// ...
/// }
/// );
/// \endcode
/// If the \p input values across threads in a block are <tt>{-1, 2, -3, 4, ..., -255, 256}</tt>, then
/// \p output values in will be <tt>{-1, 2, 2, 4, ..., 254, 256}</tt>.
/// \endparblock
template<
unsigned int ItemsPerThread,
class BinaryFunction = ::rocprim::plus<T>
>
ROCPRIM_DEVICE inline
void inclusive_scan(T (&input)[ItemsPerThread],
T (&output)[ItemsPerThread],
storage_type& storage,
BinaryFunction scan_op = BinaryFunction())
{
if(ItemsPerThread == 1)
{
base_type::inclusive_scan(input[0], output[0], storage, scan_op);
}
else
{
base_type::inclusive_scan(input, output, storage, scan_op);
}
}
/// \overload
/// \brief Performs inclusive scan across threads in a block.
///
/// * This overload does not accept storage argument. Required shared memory is
/// allocated by the method itself.
///
/// \tparam ItemsPerThread - number of items in the \p input array.
/// \tparam BinaryFunction - type of binary function used for scan. Default type
/// is rocprim::plus<T>.
///
/// \param [in] input - reference to an array containing thread input values.
/// \param [out] output - reference to a thread output array. May be aliased with \p input.
/// \param [in] scan_op - binary operation function object that will be used for scan.
/// The signature of the function should be equivalent to the following:
/// <tt>T f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
template<
unsigned int ItemsPerThread,
class BinaryFunction = ::rocprim::plus<T>
>
ROCPRIM_DEVICE inline
void inclusive_scan(T (&input)[ItemsPerThread],
T (&output)[ItemsPerThread],
BinaryFunction scan_op = BinaryFunction())
{
if(ItemsPerThread == 1)
{
base_type::inclusive_scan(input[0], output[0], scan_op);
}
else
{
base_type::inclusive_scan(input, output, scan_op);
}
}
/// \brief Performs inclusive scan and reduction across threads in a block.
///
/// \tparam ItemsPerThread - number of items in the \p input array.
/// \tparam BinaryFunction - type of binary function used for scan. Default type
/// is rocprim::plus<T>.
///
/// \param [in] input - reference to an array containing thread input values.
/// \param [out] output - reference to a thread output array. May be aliased with \p input.
/// \param [out] reduction - result of reducing of all \p input values in a block.
/// \param [in] storage - reference to a temporary storage object of type storage_type.
/// \param [in] scan_op - binary operation function object that will be used for scan.
/// The signature of the function should be equivalent to the following:
/// <tt>T f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
///
/// \par Storage reusage
/// Synchronization barrier should be placed before \p storage is reused
/// or repurposed: \p __syncthreads() in HIP, \p tile_barrier::wait() in HC, or
/// universal rocprim::syncthreads().
///
/// \par Examples
/// \parblock
/// The examples present inclusive maximum scan operations performed on a block of 128 threads,
/// each provides two \p long value.
///
/// \b HIP: \n
/// \code{.cpp}
/// __global__ void example_kernel(...) // hipBlockDim_x = 128
/// {
/// // specialize block_scan for long and block of 128 threads
/// using block_scan_f = rocprim::block_scan<long, 128>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_long::storage_type storage;
///
/// long input[2] = ...;
/// long output[2];
/// long reduction;
/// // execute inclusive min scan
/// block_scan_long().inclusive_scan(
/// input,
/// output,
/// reduction,
/// storage,
/// rocprim::maximum<long>()
/// );
/// ...
/// }
/// \endcode
///
/// \b HC: \n
/// \code{.cpp}
/// hc::parallel_for_each(
/// hc::extent<1>(...).tile(128),
/// [=](hc::tiled_index<1> i) [[hc]]
/// {
/// // specialize block_scan for long and block of 128 threads
/// using block_scan_f = rocprim::block_scan<long, 128>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_long::storage_type storage;
///
/// long input[2] = ...;
/// long output[2];
/// long reduction;
/// // execute inclusive min scan
/// block_scan_long().inclusive_scan(
/// input,
/// output,
/// reduction,
/// storage,
/// rocprim::maximum<long>()
/// );
/// ...
/// }
/// );
/// \endcode
/// If the \p input values across threads in a block are <tt>{-1, 2, -3, 4, ..., -255, 256}</tt>, then
/// \p output values in will be <tt>{-1, 2, 2, 4, ..., 254, 256}</tt> and the \p reduction will be \p 256.
/// \endparblock
template<
unsigned int ItemsPerThread,
class BinaryFunction = ::rocprim::plus<T>
>
ROCPRIM_DEVICE inline
void inclusive_scan(T (&input)[ItemsPerThread],
T (&output)[ItemsPerThread],
T& reduction,
storage_type& storage,
BinaryFunction scan_op = BinaryFunction())
{
if(ItemsPerThread == 1)
{
base_type::inclusive_scan(input[0], output[0], reduction, storage, scan_op);
}
else
{
base_type::inclusive_scan(input, output, reduction, storage, scan_op);
}
}
/// \overload
/// \brief Performs inclusive scan and reduction across threads in a block.
///
/// * This overload does not accept storage argument. Required shared memory is
/// allocated by the method itself.
///
/// \tparam ItemsPerThread - number of items in the \p input array.
/// \tparam BinaryFunction - type of binary function used for scan. Default type
/// is rocprim::plus<T>.
///
/// \param [in] input - reference to an array containing thread input values.
/// \param [out] output - reference to a thread output array. May be aliased with \p input.
/// \param [out] reduction - result of reducing of all \p input values in a block.
/// \param [in] scan_op - binary operation function object that will be used for scan.
/// The signature of the function should be equivalent to the following:
/// <tt>T f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
template<
unsigned int ItemsPerThread,
class BinaryFunction = ::rocprim::plus<T>
>
ROCPRIM_DEVICE inline
void inclusive_scan(T (&input)[ItemsPerThread],
T (&output)[ItemsPerThread],
T& reduction,
BinaryFunction scan_op = BinaryFunction())
{
if(ItemsPerThread == 1)
{
base_type::inclusive_scan(input[0], output[0], reduction, scan_op);
}
else
{
base_type::inclusive_scan(input, output, reduction, scan_op);
}
}
/// \brief Performs inclusive scan across threads in a block, and uses
/// \p prefix_callback_op to generate prefix value for the whole block.
///
/// \tparam ItemsPerThread - number of items in the \p input array.
/// \tparam PrefixCallback - type of the unary function object used for generating
/// block-wide prefix value for the scan operation.
/// \tparam BinaryFunction - type of binary function used for scan. Default type
/// is rocprim::plus<T>.
///
/// \param [in] input - reference to an array containing thread input values.
/// \param [out] output - reference to a thread output array. May be aliased with \p input.
/// \param [in] storage - reference to a temporary storage object of type storage_type.
/// \param [in,out] prefix_callback_op - function object for generating block prefix value.
/// The signature of the \p prefix_callback_op should be equivalent to the following:
/// <tt>T f(const T &block_reduction);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
/// The object will be called by the first thread in the first warp from the block with
/// block reduction of \p input values as input argument. The result will be used as the
/// block-wide prefix.
/// \param [in] scan_op - binary operation function object that will be used for scan.
/// The signature of the function should be equivalent to the following:
/// <tt>T f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
///
/// \par Storage reusage
/// Synchronization barrier should be placed before \p storage is reused
/// or repurposed: \p __syncthreads() in HIP, \p tile_barrier::wait() in HC, or
/// universal rocprim::syncthreads().
///
/// \par Examples
/// \parblock
/// The examples present inclusive prefix sum operations performed on a block of 128 threads,
/// each thread provides two \p int value.
///
/// \b HIP: \n
/// \code{.cpp}
///
/// struct my_block_prefix
/// {
/// int prefix;
///
/// __device__ my_block_prefix(int prefix) : prefix(prefix) {}
///
/// __device__ int operator()(int block_reduction)
/// {
/// int old_prefix = prefix;
/// prefix = prefix + block_reduction;
/// return old_prefix;
/// }
/// };
///
/// __global__ void example_kernel(...) // hipBlockDim_x = 128
/// {
/// // specialize block_scan for int and block of 128 threads
/// using block_scan_f = rocprim::block_scan<int, 128>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_int::storage_type storage;
///
/// // init prefix functor
/// my_block_prefix prefix_callback(10);
///
/// int input[2] = ...;
/// int output[2];
/// // execute inclusive prefix sum
/// block_scan_int().inclusive_scan(
/// input,
/// output,
/// storage,
/// prefix_callback,
/// rocprim::plus<int>()
/// );
/// ...
/// }
/// \endcode
///
/// \b HC: \n
/// \code{.cpp}
/// hc::parallel_for_each(
/// hc::extent<1>(...).tile(256),
/// [=](hc::tiled_index<1> i) [[hc]]
/// {
/// // specialize block_scan for int and block of 256 threads
/// using block_scan_f = rocprim::block_scan<int, 256>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_int::storage_type storage;
///
/// int prefix = 10;
/// auto prefix_callback = [&prefix](int reduction)
/// {
/// int old_prefix = prefix;
/// prefix += reduction;
/// return old_prefix;
/// };
///
/// int input[2] = ...;
/// int output[2];
/// // execute inclusive min scan
/// block_scan_int().inclusive_scan(
/// input,
/// output,
/// storage,
/// prefix_callback,
/// rocprim::plus<int>()
/// );
/// ...
/// }
/// );
/// \endcode
/// If the \p input values across threads in a block are <tt>{1, 1, 1, ..., 1}</tt>, then
/// \p output values in will be <tt>{11, 12, 13, ..., 266}</tt>, and the \p prefix will
/// be <tt>266</tt>.
/// \endparblock
template<
unsigned int ItemsPerThread,
class PrefixCallback,
class BinaryFunction
>
ROCPRIM_DEVICE inline
void inclusive_scan(T (&input)[ItemsPerThread],
T (&output)[ItemsPerThread],
storage_type& storage,
PrefixCallback& prefix_callback_op,
BinaryFunction scan_op)
{
if(ItemsPerThread == 1)
{
base_type::inclusive_scan(input[0], output[0], storage, prefix_callback_op, scan_op);
}
else
{
base_type::inclusive_scan(input, output, storage, prefix_callback_op, scan_op);
}
}
/// \brief Performs exclusive scan across threads in a block.
///
/// \tparam BinaryFunction - type of binary function used for scan. Default type
/// is rocprim::plus<T>.
///
/// \param [in] input - thread input value.
/// \param [out] output - reference to a thread output value. May be aliased with \p input.
/// \param [in] storage - reference to a temporary storage object of type storage_type.
/// \param [in] init - initial value used to start the exclusive scan. Should be the same
/// for all threads in a block.
/// \param [in] scan_op - binary operation function object that will be used for scan.
/// The signature of the function should be equivalent to the following:
/// <tt>T f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
///
/// \par Storage reusage
/// Synchronization barrier should be placed before \p storage is reused
/// or repurposed: \p __syncthreads() in HIP, \p tile_barrier::wait() in HC, or
/// universal rocprim::syncthreads().
///
/// \par Examples
/// \parblock
/// The examples present exclusive min scan operations performed on a block of 256 threads,
/// each provides one \p float value.
///
/// \b HIP: \n
/// \code{.cpp}
/// __global__ void example_kernel(...) // hipBlockDim_x = 256
/// {
/// // specialize block_scan for float and block of 256 threads
/// using block_scan_f = rocprim::block_scan<float, 256>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_float::storage_type storage;
///
/// float init = ...;
/// float input = ...;
/// float output;
/// // execute exclusive min scan
/// block_scan_float().exclusive_scan(
/// input,
/// output,
/// init,
/// storage,
/// rocprim::minimum<float>()
/// );
/// ...
/// }
/// \endcode
///
/// \b HC: \n
/// \code{.cpp}
/// hc::parallel_for_each(
/// hc::extent<1>(...).tile(256),
/// [=](hc::tiled_index<1> i) [[hc]]
/// {
/// // specialize block_scan for float and block of 256 threads
/// using block_scan_f = rocprim::block_scan<float, 256>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_float::storage_type storage;
///
/// float init = ...;
/// float input = ...;
/// float output;
/// // execute exclusive min scan
/// block_scan_float().exclusive_scan(
/// input,
/// output,
/// init,
/// storage,
/// rocprim::minimum<float>()
/// );
/// ...
/// }
/// );
/// \endcode
/// If the \p input values across threads in a block are <tt>{1, -2, 3, -4, ..., 255, -256}</tt>
/// and \p init is \p 0, then \p output values in will be <tt>{0, 0, -2, -2, -4, ..., -254, -254}</tt>.
/// \endparblock
template<class BinaryFunction = ::rocprim::plus<T>>
ROCPRIM_DEVICE inline
void exclusive_scan(T input,
T& output,
T init,
storage_type& storage,
BinaryFunction scan_op = BinaryFunction())
{
base_type::exclusive_scan(input, output, init, storage, scan_op);
}
/// \overload
/// \brief Performs exclusive scan across threads in a block.
///
/// * This overload does not accept storage argument. Required shared memory is
/// allocated by the method itself.
///
/// \tparam BinaryFunction - type of binary function used for scan. Default type
/// is rocprim::plus<T>.
///
/// \param [in] input - thread input value.
/// \param [out] output - reference to a thread output value. May be aliased with \p input.
/// \param [in] init - initial value used to start the exclusive scan. Should be the same
/// for all threads in a block.
/// \param [in] scan_op - binary operation function object that will be used for scan.
/// The signature of the function should be equivalent to the following:
/// <tt>T f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
template<class BinaryFunction = ::rocprim::plus<T>>
ROCPRIM_DEVICE inline
void exclusive_scan(T input,
T& output,
T init,
BinaryFunction scan_op = BinaryFunction())
{
base_type::exclusive_scan(input, output, init, scan_op);
}
/// \brief Performs exclusive scan and reduction across threads in a block.
///
/// \tparam BinaryFunction - type of binary function used for scan. Default type
/// is rocprim::plus<T>.
///
/// \param [in] input - thread input value.
/// \param [out] output - reference to a thread output value. May be aliased with \p input.
/// \param [in] init - initial value used to start the exclusive scan. Should be the same
/// for all threads in a block.
/// \param [out] reduction - result of reducing of all \p input values in a block.
/// \param [in] storage - reference to a temporary storage object of type storage_type.
/// \param [in] scan_op - binary operation function object that will be used for scan.
/// The signature of the function should be equivalent to the following:
/// <tt>T f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
///
/// \par Storage reusage
/// Synchronization barrier should be placed before \p storage is reused
/// or repurposed: \p __syncthreads() in HIP, \p tile_barrier::wait() in HC, or
/// universal rocprim::syncthreads().
///
/// \par Examples
/// \parblock
/// The examples present exclusive min scan operations performed on a block of 256 threads,
/// each provides one \p float value.
///
/// \b HIP: \n
/// \code{.cpp}
/// __global__ void example_kernel(...) // hipBlockDim_x = 256
/// {
/// // specialize block_scan for float and block of 256 threads
/// using block_scan_f = rocprim::block_scan<float, 256>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_float::storage_type storage;
///
/// float init = 0;
/// float input = ...;
/// float output;
/// float reduction;
/// // execute exclusive min scan
/// block_scan_float().exclusive_scan(
/// input,
/// output,
/// init,
/// reduction,
/// storage,
/// rocprim::minimum<float>()
/// );
/// ...
/// }
/// \endcode
///
/// \b HC: \n
/// \code{.cpp}
/// hc::parallel_for_each(
/// hc::extent<1>(...).tile(256),
/// [=](hc::tiled_index<1> i) [[hc]]
/// {
/// // specialize block_scan for float and block of 256 threads
/// using block_scan_f = rocprim::block_scan<float, 256>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_float::storage_type storage;
///
/// float init = 0;
/// float input = ...;
/// float output;
/// float reduction;
/// // execute exclusive min scan
/// block_scan_float().exclusive_scan(
/// input,
/// output,
/// init,
/// reduction,
/// storage,
/// rocprim::minimum<float>()
/// );
/// ...
/// }
/// );
/// \endcode
/// If the \p input values across threads in a block are <tt>{1, -2, 3, -4, ..., 255, -256}</tt>
/// and \p init is \p 0, then \p output values in will be <tt>{0, 0, -2, -2, -4, ..., -254, -254}</tt>
/// and the \p reduction will be \p -256.
/// \endparblock
template<class BinaryFunction = ::rocprim::plus<T>>
ROCPRIM_DEVICE inline
void exclusive_scan(T input,
T& output,
T init,
T& reduction,
storage_type& storage,
BinaryFunction scan_op = BinaryFunction())
{
base_type::exclusive_scan(input, output, init, reduction, storage, scan_op);
}
/// \overload
/// \brief Performs exclusive scan and reduction across threads in a block.
///
/// * This overload does not accept storage argument. Required shared memory is
/// allocated by the method itself.
///
/// \tparam BinaryFunction - type of binary function used for scan. Default type
/// is rocprim::plus<T>.
///
/// \param [in] input - thread input value.
/// \param [out] output - reference to a thread output value. May be aliased with \p input.
/// \param [in] init - initial value used to start the exclusive scan. Should be the same
/// for all threads in a block.
/// \param [out] reduction - result of reducing of all \p input values in a block.
/// \param [in] scan_op - binary operation function object that will be used for scan.
/// The signature of the function should be equivalent to the following:
/// <tt>T f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
template<class BinaryFunction = ::rocprim::plus<T>>
ROCPRIM_DEVICE inline
void exclusive_scan(T input,
T& output,
T init,
T& reduction,
BinaryFunction scan_op = BinaryFunction())
{
base_type::exclusive_scan(input, output, init, reduction, scan_op);
}
/// \brief Performs exclusive scan across threads in a block, and uses
/// \p prefix_callback_op to generate prefix value for the whole block.
///
/// \tparam PrefixCallback - type of the unary function object used for generating
/// block-wide prefix value for the scan operation.
/// \tparam BinaryFunction - type of binary function used for scan. Default type
/// is rocprim::plus<T>.
///
/// \param [in] input - thread input value.
/// \param [out] output - reference to a thread output value. May be aliased with \p input.
/// \param [in] storage - reference to a temporary storage object of type storage_type.
/// \param [in,out] prefix_callback_op - function object for generating block prefix value.
/// The signature of the \p prefix_callback_op should be equivalent to the following:
/// <tt>T f(const T &block_reduction);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
/// The object will be called by the first thread in the first warp from the block with
/// block reduction of \p input values as input argument. The result will be used as the
/// block-wide prefix.
/// \param [in] scan_op - binary operation function object that will be used for scan.
/// The signature of the function should be equivalent to the following:
/// <tt>T f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
///
/// \par Storage reusage
/// Synchronization barrier should be placed before \p storage is reused
/// or repurposed: \p __syncthreads() in HIP, \p tile_barrier::wait() in HC, or
/// universal rocprim::syncthreads().
///
/// \par Examples
/// \parblock
/// The examples present exclusive prefix sum operations performed on a block of 256 threads,
/// each thread provides one \p int value.
///
/// \b HIP: \n
/// \code{.cpp}
///
/// struct my_block_prefix
/// {
/// int prefix;
///
/// __device__ my_block_prefix(int prefix) : prefix(prefix) {}
///
/// __device__ int operator()(int block_reduction)
/// {
/// int old_prefix = prefix;
/// prefix = prefix + block_reduction;
/// return old_prefix;
/// }
/// };
///
/// __global__ void example_kernel(...) // hipBlockDim_x = 256
/// {
/// // specialize block_scan for int and block of 256 threads
/// using block_scan_f = rocprim::block_scan<int, 256>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_int::storage_type storage;
///
/// // init prefix functor
/// my_block_prefix prefix_callback(10);
///
/// int input;
/// int output;
/// // execute exclusive prefix sum
/// block_scan_int().exclusive_scan(
/// input,
/// output,
/// storage,
/// prefix_callback,
/// rocprim::plus<int>()
/// );
/// ...
/// }
/// \endcode
///
/// \b HC: \n
/// \code{.cpp}
/// hc::parallel_for_each(
/// hc::extent<1>(...).tile(256),
/// [=](hc::tiled_index<1> i) [[hc]]
/// {
/// // specialize block_scan for int and block of 256 threads
/// using block_scan_f = rocprim::block_scan<int, 256>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_int::storage_type storage;
///
/// int prefix = 10;
/// auto prefix_callback = [&prefix](int reduction)
/// {
/// int old_prefix = prefix;
/// prefix += reduction;
/// return old_prefix;
/// };
///
/// int input = ...;
/// int output;
/// // execute exclusive min scan
/// block_scan_int().exclusive_scan(
/// input,
/// output,
/// storage,
/// prefix_callback,
/// rocprim::plus<int>()
/// );
/// ...
/// }
/// );
/// \endcode
/// If the \p input values across threads in a block are <tt>{1, 1, 1, ..., 1}</tt>, then
/// \p output values in will be <tt>{10, 11, 12, 13, ..., 265}</tt>, and the \p prefix will
/// be <tt>266</tt>.
/// \endparblock
template<
class PrefixCallback,
class BinaryFunction = ::rocprim::plus<T>
>
ROCPRIM_DEVICE inline
void exclusive_scan(T input,
T& output,
storage_type& storage,
PrefixCallback& prefix_callback_op,
BinaryFunction scan_op)
{
base_type::exclusive_scan(input, output, storage, prefix_callback_op, scan_op);
}
/// \brief Performs exclusive scan across threads in a block.
///
/// \tparam ItemsPerThread - number of items in the \p input array.
/// \tparam BinaryFunction - type of binary function used for scan. Default type
/// is rocprim::plus<T>.
///
/// \param [in] input - reference to an array containing thread input values.
/// \param [out] output - reference to a thread output array. May be aliased with \p input.
/// \param [in] init - initial value used to start the exclusive scan. Should be the same
/// for all threads in a block.
/// \param [in] storage - reference to a temporary storage object of type storage_type.
/// \param [in] scan_op - binary operation function object that will be used for scan.
/// The signature of the function should be equivalent to the following:
/// <tt>T f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
///
/// \par Storage reusage
/// Synchronization barrier should be placed before \p storage is reused
/// or repurposed: \p __syncthreads() in HIP, \p tile_barrier::wait() in HC, or
/// universal rocprim::syncthreads().
///
/// \par Examples
/// \parblock
/// The examples present exclusive maximum scan operations performed on a block of 128 threads,
/// each provides two \p long value.
///
/// \b HIP: \n
/// \code{.cpp}
/// __global__ void example_kernel(...) // hipBlockDim_x = 128
/// {
/// // specialize block_scan for long and block of 128 threads
/// using block_scan_f = rocprim::block_scan<long, 128>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_long::storage_type storage;
///
/// long init = ...;
/// long input[2] = ...;
/// long output[2];
/// // execute exclusive min scan
/// block_scan_long().exclusive_scan(
/// input,
/// output,
/// init,
/// storage,
/// rocprim::maximum<long>()
/// );
/// ...
/// }
/// \endcode
///
/// \b HC: \n
/// \code{.cpp}
/// hc::parallel_for_each(
/// hc::extent<1>(...).tile(128),
/// [=](hc::tiled_index<1> i) [[hc]]
/// {
/// // specialize block_scan for long and block of 128 threads
/// using block_scan_f = rocprim::block_scan<long, 128>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_long::storage_type storage;
///
/// long init = ...;
/// long input[2] = ...;
/// long output[2];
/// // execute exclusive min scan
/// block_scan_long().exclusive_scan(
/// input,
/// output,
/// init,
/// storage,
/// rocprim::maximum<long>()
/// );
/// ...
/// }
/// );
/// \endcode
/// If the \p input values across threads in a block are <tt>{-1, 2, -3, 4, ..., -255, 256}</tt>
/// and \p init is 0, then \p output values in will be <tt>{0, 0, 2, 2, 4, ..., 254, 254}</tt>.
/// \endparblock
template<
unsigned int ItemsPerThread,
class BinaryFunction = ::rocprim::plus<T>
>
ROCPRIM_DEVICE inline
void exclusive_scan(T (&input)[ItemsPerThread],
T (&output)[ItemsPerThread],
T init,
storage_type& storage,
BinaryFunction scan_op = BinaryFunction())
{
if(ItemsPerThread == 1)
{
base_type::exclusive_scan(input[0], output[0], init, storage, scan_op);
}
else
{
base_type::exclusive_scan(input, output, init, storage, scan_op);
}
}
/// \overload
/// \brief Performs exclusive scan across threads in a block.
///
/// * This overload does not accept storage argument. Required shared memory is
/// allocated by the method itself.
///
/// \tparam ItemsPerThread - number of items in the \p input array.
/// \tparam BinaryFunction - type of binary function used for scan. Default type
/// is rocprim::plus<T>.
///
/// \param [in] input - reference to an array containing thread input values.
/// \param [out] output - reference to a thread output array. May be aliased with \p input.
/// \param [in] init - initial value used to start the exclusive scan. Should be the same
/// for all threads in a block.
/// \param [in] scan_op - binary operation function object that will be used for scan.
/// The signature of the function should be equivalent to the following:
/// <tt>T f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
template<
unsigned int ItemsPerThread,
class BinaryFunction = ::rocprim::plus<T>
>
ROCPRIM_DEVICE inline
void exclusive_scan(T (&input)[ItemsPerThread],
T (&output)[ItemsPerThread],
T init,
BinaryFunction scan_op = BinaryFunction())
{
if(ItemsPerThread == 1)
{
base_type::exclusive_scan(input[0], output[0], init, scan_op);
}
else
{
base_type::exclusive_scan(input, output, init, scan_op);
}
}
/// \brief Performs exclusive scan and reduction across threads in a block.
///
/// \tparam ItemsPerThread - number of items in the \p input array.
/// \tparam BinaryFunction - type of binary function used for scan. Default type
/// is rocprim::plus<T>.
///
/// \param [in] input - reference to an array containing thread input values.
/// \param [out] output - reference to a thread output array. May be aliased with \p input.
/// \param [in] init - initial value used to start the exclusive scan. Should be the same
/// for all threads in a block.
/// \param [out] reduction - result of reducing of all \p input values in a block.
/// \param [in] storage - reference to a temporary storage object of type storage_type.
/// \param [in] scan_op - binary operation function object that will be used for scan.
/// The signature of the function should be equivalent to the following:
/// <tt>T f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
///
/// \par Storage reusage
/// Synchronization barrier should be placed before \p storage is reused
/// or repurposed: \p __syncthreads() in HIP, \p tile_barrier::wait() in HC, or
/// universal rocprim::syncthreads().
///
/// \par Examples
/// \parblock
/// The examples present exclusive maximum scan operations performed on a block of 128 threads,
/// each provides two \p long value.
///
/// \b HIP: \n
/// \code{.cpp}
/// __global__ void example_kernel(...) // hipBlockDim_x = 128
/// {
/// // specialize block_scan for long and block of 128 threads
/// using block_scan_f = rocprim::block_scan<long, 128>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_long::storage_type storage;
///
/// long init = ...;
/// long input[2] = ...;
/// long output[2];
/// long reduction;
/// // execute exclusive min scan
/// block_scan_long().exclusive_scan(
/// input,
/// output,
/// init,
/// reduction,
/// storage,
/// rocprim::maximum<long>()
/// );
/// ...
/// }
/// \endcode
///
/// \b HC: \n
/// \code{.cpp}
/// hc::parallel_for_each(
/// hc::extent<1>(...).tile(128),
/// [=](hc::tiled_index<1> i) [[hc]]
/// {
/// // specialize block_scan for long and block of 128 threads
/// using block_scan_f = rocprim::block_scan<long, 128>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_long::storage_type storage;
///
/// long init = ...;
/// long input[2] = ...;
/// long output[2];
/// long reduction;
/// // execute exclusive min scan
/// block_scan_long().exclusive_scan(
/// input,
/// output,
/// init,
/// reduction,
/// storage,
/// rocprim::maximum<long>()
/// );
/// ...
/// }
/// );
/// \endcode
/// If the \p input values across threads in a block are <tt>{-1, 2, -3, 4, ..., -255, 256}</tt>
/// and \p init is 0, then \p output values in will be <tt>{0, 0, 2, 2, 4, ..., 254, 254}</tt>
/// and the \p reduction will be \p 256.
/// \endparblock
template<
unsigned int ItemsPerThread,
class BinaryFunction = ::rocprim::plus<T>
>
ROCPRIM_DEVICE inline
void exclusive_scan(T (&input)[ItemsPerThread],
T (&output)[ItemsPerThread],
T init,
T& reduction,
storage_type& storage,
BinaryFunction scan_op = BinaryFunction())
{
if(ItemsPerThread == 1)
{
base_type::exclusive_scan(input[0], output[0], init, reduction, storage, scan_op);
}
else
{
base_type::exclusive_scan(input, output, init, reduction, storage, scan_op);
}
}
/// \overload
/// \brief Performs exclusive scan and reduction across threads in a block.
///
/// * This overload does not accept storage argument. Required shared memory is
/// allocated by the method itself.
///
/// \tparam ItemsPerThread - number of items in the \p input array.
/// \tparam BinaryFunction - type of binary function used for scan. Default type
/// is rocprim::plus<T>.
///
/// \param [in] input - reference to an array containing thread input values.
/// \param [out] output - reference to a thread output array. May be aliased with \p input.
/// \param [in] init - initial value used to start the exclusive scan. Should be the same
/// for all threads in a block.
/// \param [out] reduction - result of reducing of all \p input values in a block.
/// \param [in] scan_op - binary operation function object that will be used for scan.
/// The signature of the function should be equivalent to the following:
/// <tt>T f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
template<
unsigned int ItemsPerThread,
class BinaryFunction = ::rocprim::plus<T>
>
ROCPRIM_DEVICE inline
void exclusive_scan(T (&input)[ItemsPerThread],
T (&output)[ItemsPerThread],
T init,
T& reduction,
BinaryFunction scan_op = BinaryFunction())
{
if(ItemsPerThread == 1)
{
base_type::exclusive_scan(input[0], output[0], init, reduction, scan_op);
}
else
{
base_type::exclusive_scan(input, output, init, reduction, scan_op);
}
}
/// \brief Performs exclusive scan across threads in a block, and uses
/// \p prefix_callback_op to generate prefix value for the whole block.
///
/// \tparam ItemsPerThread - number of items in the \p input array.
/// \tparam PrefixCallback - type of the unary function object used for generating
/// block-wide prefix value for the scan operation.
/// \tparam BinaryFunction - type of binary function used for scan. Default type
/// is rocprim::plus<T>.
///
/// \param [in] input - reference to an array containing thread input values.
/// \param [out] output - reference to a thread output array. May be aliased with \p input.
/// \param [in] storage - reference to a temporary storage object of type storage_type.
/// \param [in,out] prefix_callback_op - function object for generating block prefix value.
/// The signature of the \p prefix_callback_op should be equivalent to the following:
/// <tt>T f(const T &block_reduction);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
/// The object will be called by the first thread in the first warp from the block with
/// block reduction of \p input values as input argument. The result will be used as the
/// block-wide prefix.
/// \param [in] scan_op - binary operation function object that will be used for scan.
/// The signature of the function should be equivalent to the following:
/// <tt>T f(const T &a, const T &b);</tt>. The signature does not need to have
/// <tt>const &</tt>, but function object must not modify the objects passed to it.
///
/// \par Storage reusage
/// Synchronization barrier should be placed before \p storage is reused
/// or repurposed: \p __syncthreads() in HIP, \p tile_barrier::wait() in HC, or
/// universal rocprim::syncthreads().
///
/// \par Examples
/// \parblock
/// The examples present exclusive prefix sum operations performed on a block of 128 threads,
/// each thread provides two \p int value.
///
/// \b HIP: \n
/// \code{.cpp}
///
/// struct my_block_prefix
/// {
/// int prefix;
///
/// __device__ my_block_prefix(int prefix) : prefix(prefix) {}
///
/// __device__ int operator()(int block_reduction)
/// {
/// int old_prefix = prefix;
/// prefix = prefix + block_reduction;
/// return old_prefix;
/// }
/// };
///
/// __global__ void example_kernel(...) // hipBlockDim_x = 128
/// {
/// // specialize block_scan for int and block of 128 threads
/// using block_scan_f = rocprim::block_scan<int, 128>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_int::storage_type storage;
///
/// // init prefix functor
/// my_block_prefix prefix_callback(10);
///
/// int input[2] = ...;
/// int output[2];
/// // execute exclusive prefix sum
/// block_scan_int().exclusive_scan(
/// input,
/// output,
/// storage,
/// prefix_callback,
/// rocprim::plus<int>()
/// );
/// ...
/// }
/// \endcode
///
/// \b HC: \n
/// \code{.cpp}
/// hc::parallel_for_each(
/// hc::extent<1>(...).tile(256),
/// [=](hc::tiled_index<1> i) [[hc]]
/// {
/// // specialize block_scan for int and block of 256 threads
/// using block_scan_f = rocprim::block_scan<int, 256>;
/// // allocate storage in shared memory for the block
/// __shared__ block_scan_int::storage_type storage;
///
/// int prefix = 10;
/// auto prefix_callback = [&prefix](int reduction)
/// {
/// int old_prefix = prefix;
/// prefix += reduction;
/// return old_prefix;
/// };
///
/// int input[2] = ...;
/// int output[2];
/// // execute exclusive min scan
/// block_scan_int().exclusive_scan(
/// input,
/// output,
/// storage,
/// prefix_callback,
/// rocprim::plus<int>()
/// );
/// ...
/// }
/// );
/// \endcode
/// If the \p input values across threads in a block are <tt>{1, 1, 1, ..., 1}</tt>, then
/// \p output values in will be <tt>{10, 11, 12, 13, ..., 265}</tt>, and the \p prefix will
/// be <tt>266</tt>.
/// \endparblock
template<
unsigned int ItemsPerThread,
class PrefixCallback,
class BinaryFunction
>
ROCPRIM_DEVICE inline
void exclusive_scan(T (&input)[ItemsPerThread],
T (&output)[ItemsPerThread],
storage_type& storage,
PrefixCallback& prefix_callback_op,
BinaryFunction scan_op)
{
if(ItemsPerThread == 1)
{
base_type::exclusive_scan(input[0], output[0], storage, prefix_callback_op, scan_op);
}
else
{
base_type::exclusive_scan(input, output, storage, prefix_callback_op, scan_op);
}
}
};
END_ROCPRIM_NAMESPACE
/// @}
// end of group blockmodule
#endif // ROCPRIM_BLOCK_BLOCK_SCAN_HPP_
|
%ifndef MEMORY_ASM_
%define MEMORY_ASM_
%include "return.asm"
%include "atomic.asm"
memory:
.init:
; first, check already initialized
mov rdi, .initialized
call atomic.trylock
jc return.false
; check size of the installed memory
call .calcsize
; if memory not enough, return
cmp rdi, 2 * 1024 * 1024
jb return.false
; initialize memory map
call .initmap
jmp return.true
; out: di = memory size
.calcsize:
; first, disable caching
mov rax, cr0
push rax
or rax, 0x60000000 ; set CD, NW
mov cr0, rax
; then, check installed
mov rax, 1 << 36 ; 64 GiB
mov rsi, rax
mov rdi, rax
call .check
jnc .calcsize.3
xor rdi, rdi
mov r8, 36 - 3
.calcsize.1:
dec r8
jz .calcsize.3
mov rax, rdi
add rax, rsi
shr rax, 1
call .check
jc .calcsize.2
mov rdi, rax
jmp .calcsize.1
.calcsize.2:
mov rsi, rax
jmp .calcsize.1
.calcsize.3:
; enable caching
pop rax
mov cr0, rax
; save memory size
mov [.size], rdi
ret
; map begins 0x00100000
; note:
; memory size >= 0x00200000
; 0x00100000--0x0010001f: free space
; 0x00100020--0x00100000 + .size / (4096 * 8): memory management area
; in the area, page id = (addr - 0x00100000) * 8 + bit pos [addr]
; page address = id * 4096
; in: di = memory size
.initmap:
mov rcx, rdi
shr rcx, 12 + 3 + 2 ; 1 page 4 KiB per 1 bit = 128 KiB per 1 DWord
mov edi, 0x00100000
mov esi, edi
xor edx, edx
.initmap.1:
mov [edi], edx
add edi, 4
dec ecx
jnz .initmap.1
; map ends edi. set fill flag.
; Incidentally, allocate sequencial buffer for the kernel
mov [global_page_addr], edi
shr edi, 12
add edi, global_page_size ; number of allocate pages
mov eax, edi
and eax, 0x07
shr edi, 3
add edi, esi
not edx
.initmap.2:
mov [esi], edx
add esi, 4
cmp esi, edi
jb .initmap.2
mov ecx, edx
test eax, eax
jz .initmap.4
.initmap.3:
shl ecx, 1
dec eax
jz .initmap.4
jmp .initmap.3
.initmap.4:
not ecx
mov [esi], ecx
ret
; in: a = assuming size of installed memory
.check:
mov rdx, [rax - 8]
mov rcx, rdx
not rdx
mov [rax - 8], rdx
wbinvd
cmp rdx, [rax - 8]
mov [rax - 8], rcx
je return.true
jmp return.false
; out: a = size of installed memory
.getsize:
mov rax, [.size]
ret
; out: a = page address
.newpage:
pushs d, si, di
xor rax, rax
mov edi, [fs:TLS.memory.tablelookahead]
mov esi, edi
.newpage.2:
; try to set a bit
mov eax, [edi]
mov edx, eax
inc edx
jz .newpage.3
or edx, eax
lock cmpxchg [edi], edx
jne .newpage.2
; then, get bit's position
xor eax, edx ; only single bit on
dec eax
popcnt eax, eax
; then, get page address
mov [fs:TLS.memory.tablelookahead], edi
sub edi, 0x00100000 ; least 2 bits are cleared
shl edi, 3 ; make least 5 bits are cleard
add eax, edi ; calc the id,
shl rax, 12 ; and calc the address
pops d, si, di
ret
.newpage.3:
add edi, 4
cmp esi, edi
je return.false
call .getsize
shr rax, 12 + 3
add eax, 0x00100000
cmp edi, eax
jb .newpage.2
mov edi, 0x00100020
jmp .newpage.2
; in: a = page address
.disposepage:
pushs c, d, di
shr rax, 12
mov edi, eax
mov ecx, eax
shr edi, 3
and edi, ~0x03
add edi, 0x00100000
and ecx, 0x1f
mov edx, 1
shl edx, cl
not edx
.disposepage.1:
mov eax, [edi]
mov ecx, eax
and ecx, edx
lock cmpxchg [edi], ecx
jne .disposepage.1
pops c, d, di
ret
; in: a = page address
.zerofill:
pushs a, c, d
xor edx, edx
mov ecx, 4096 / 4
.zerofill.1:
mov [rax], edx
add rax, 4
dec ecx
jnz .zerofill.1
pops a, c, d
ret
.size: dq 0
.initialized: dd 0
%endif
|
; A025169: a(n) = 2*Fibonacci(2*n+2).
; 2,6,16,42,110,288,754,1974,5168,13530,35422,92736,242786,635622,1664080,4356618,11405774,29860704,78176338,204668310,535828592,1402817466,3672623806,9615053952,25172538050,65902560198,172535142544,451702867434,1182573459758,3096017511840,8105479075762,21220419715446,55555780070576,145446920496282,380784981418270,996908023758528,2609939089857314,6832909245813414
mov $2,2
lpb $0,1
sub $0,1
add $1,$2
add $2,$1
lpe
add $1,$2
|
; A178226: Characteristic function of A154809 (numbers that are not binary palindromes)
; 0,0,1,0,1,0,1,0,1,0,1,1,1,1,1,0,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
cal $0,55945 ; n - reversal of base 2 digits of n (and then the result is written in base 10).
mov $1,1
lpb $1,1
mov $1,$0
lpe
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r12
push %r13
push %r9
push %rbx
push %rdi
push %rsi
lea addresses_UC_ht+0x10fe9, %rbx
nop
nop
nop
nop
xor %r10, %r10
mov $0x6162636465666768, %r12
movq %r12, (%rbx)
nop
nop
nop
and $10786, %r13
lea addresses_A_ht+0x14de9, %rdi
nop
add %r9, %r9
vmovups (%rdi), %ymm3
vextracti128 $0, %ymm3, %xmm3
vpextrq $0, %xmm3, %rsi
nop
nop
cmp %r10, %r10
lea addresses_D_ht+0x13c29, %rdi
nop
nop
nop
nop
nop
cmp %rsi, %rsi
mov $0x6162636465666768, %r10
movq %r10, %xmm1
and $0xffffffffffffffc0, %rdi
vmovaps %ymm1, (%rdi)
nop
nop
nop
nop
nop
sub $12254, %r13
pop %rsi
pop %rdi
pop %rbx
pop %r9
pop %r13
pop %r12
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r13
push %r14
push %r15
push %r9
push %rax
push %rbp
push %rsi
// Store
lea addresses_UC+0x1dde9, %r14
nop
nop
nop
nop
nop
xor %r15, %r15
mov $0x5152535455565758, %rsi
movq %rsi, %xmm2
movups %xmm2, (%r14)
xor $50903, %rbp
// Store
mov $0xa93d900000007e9, %rax
nop
nop
nop
inc %r9
movw $0x5152, (%rax)
nop
nop
nop
nop
add %r14, %r14
// Faulty Load
lea addresses_normal+0x1bde9, %rsi
clflush (%rsi)
nop
nop
nop
nop
nop
cmp $63382, %r15
vmovntdqa (%rsi), %ymm3
vextracti128 $0, %ymm3, %xmm3
vpextrq $1, %xmm3, %r14
lea oracles, %rsi
and $0xff, %r14
shlq $12, %r14
mov (%rsi,%r14,1), %r14
pop %rsi
pop %rbp
pop %rax
pop %r9
pop %r15
pop %r14
pop %r13
ret
/*
<gen_faulty_load>
[REF]
{'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_normal', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 8, 'NT': False, 'type': 'addresses_UC', 'size': 16, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_NC', 'size': 2, 'AVXalign': False}}
[Faulty Load]
{'src': {'same': True, 'congruent': 0, 'NT': True, 'type': 'addresses_normal', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 8, 'NT': False, 'type': 'addresses_UC_ht', 'size': 8, 'AVXalign': False}}
{'src': {'same': False, 'congruent': 10, 'NT': False, 'type': 'addresses_A_ht', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 2, 'NT': False, 'type': 'addresses_D_ht', 'size': 32, 'AVXalign': True}}
{'00': 274}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
; A004632: Cubes written in base 2.
; 1,1000,11011,1000000,1111101,11011000,101010111,1000000000,1011011001,1111101000,10100110011,11011000000,100010010101,101010111000,110100101111,1000000000000,1001100110001,1011011001000,1101011001011,1111101000000,10010000101101,10100110011000,10111110000111,11011000000000,11110100001001,100010010101000,100110011100011,101010111000000,101111101000101,110100101111000,111010001011111,1000000000000000,1000110001100001,1001100110001000,1010011101111011,1011011001000000,1100010111011101,1101011001011000,1110011110110111,1111101000000000,10000110100111001,10010000101101000,10011011010010011,10100110011000000,10110001111110101,10111110000111000,11001010110001111,11011000000000000,11100101110010001,11110100001001000,100000011000101011,100010010101000000,100100010110001101,100110011100011000,101000100111100111,101010111000000000,101101001101101001,101111101000101000,110010001001000011,110100101111000000,110111011010100101,111010001011111000,111101000010111111,1000000000000000000,1000011000011000001,1000110001100001000,1001001011011011011,1001100110001000000,1010000001100111101,1010011101111011000,1010111011000010111,1011011001000000000,1011110111110011001,1100010111011101000,1100110111111110011,1101011001011000000,1101111011101010101,1110011110110111000,1111000010111101111,1111101000000000000,10000001101111110001,10000110100111001000,10001011100110001011,10010000101101000000,10010101111011101101,10011011010010011000,10100000110001000111,10100110011000000000,10101100000111001001,10110001111110101000,10110111111110100011,10111110000111000000,11000100011000000101,11001010110001111000,11010001010100011111,11011000000000000000,11011110110100100001,11100101110010001000,11101100111000111011,11110100001001000000
add $0,1
pow $0,3
seq $0,5836 ; Numbers n whose base 3 representation contains no 2.
seq $0,7089 ; Numbers in base 3.
|
; A183221: Complement of the 9-gonal numbers.
; 2,3,4,5,6,7,8,10,11,12,13,14,15,16,17,18,19,20,21,22,23,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105
mov $2,$0
lpb $2
add $0,1
add $1,7
sub $2,$1
lpe
add $0,2
|
; A124678: Number of conjugacy classes in PSL_2(p), p = prime(n).
; 3,4,5,6,8,9,11,12,14,17,18,21,23,24,26,29,32,33,36,38,39,42,44,47,51,53,54,56,57,59,66,68,71,72,77,78,81,84,86,89,92,93,98,99,101,102,108,114,116,117,119,122,123,128,131,134,137,138,141,143,144,149,156,158,159,161,168,171,176,177,179,182,186,189,192,194,197,201,203,207,212,213,218,219,222,224,227,231,233,234,236,242,246,248,252,254,257,263,264,273,276,281,284,287,288,291,296,299,302,303,306,309,311,312,318,323,324,326,329,332,333,339,341,344,348,353,357,362,366,369,372,374,378,381,383,387,389,396,401,407,408,413,414,416,417,422,429,431,432,434,441,443,444,446,456,458,462,467,471,473,476,479,486,488,491,494,498,501,507,509,512,513,518,519,522,527,528,533,534,537,546,548,549,551,554,557,561,564,567,578,579,584,588,593,596,599,603,609,611,614,617,618,621,627,632,641,642,644,647,648,651,653,654,656,662,663,666,683,686,689,693,702,707,714,716,717,719,722,726,728,729,732,738,743,744,746,747,749,752,758,764,768,774,777,779,782,786,788,792,794
mov $2,$0
cal $0,173072 ; n-th prime minus n-th even number.
add $0,12
mov $1,$0
sub $1,13
div $1,2
add $1,3
add $1,$2
|
;
; PC-6001 specific routines
; by Stefano Bodrato, Fall 2013
;
; int set_psg(int reg, int val);
;
; Play a sound by PSG
;
;
; $Id: set_psg.asm,v 1.3 2016/06/10 21:13:58 dom Exp $
;
SECTION code_clib
PUBLIC set_psg
PUBLIC _set_psg
EXTERN set_psg_callee
EXTERN ASMDISP_SET_PSG_CALLEE
set_psg:
_set_psg:
pop bc
pop de
pop hl
push hl
push de
push bc
jp set_psg_callee + ASMDISP_SET_PSG_CALLEE
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Copyright (c) 2012, Intel Corporation
;
; All rights reserved.
;
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions are
; met:
;
; * Redistributions of source code must retain the above copyright
; notice, this list of conditions and the following disclaimer.
;
; * 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.
;
; * Neither the name of the Intel Corporation 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 INTEL CORPORATION "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 INTEL CORPORATION 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.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; Example YASM command lines:
; Windows: yasm -Xvc -f x64 -rnasm -pnasm -o sha256_avx2_rorx8.obj -g cv8 sha256_avx2_rorx8.asm
; Linux: yasm -f x64 -f elf64 -X gnu -g dwarf2 -D LINUX -o sha256_avx2_rorx8.o sha256_avx2_rorx8.asm
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; This code is described in an Intel White-Paper:
; "Fast SHA-256 Implementations on Intel Architecture Processors"
;
; To find it, surf to http://www.intel.com/p/en_US/embedded
; and search for that title.
; The paper is expected to be released roughly at the end of April, 2012
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; This code schedules 8 blocks at a time, with 1 lane per block
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Define Macros
%macro addm 2
add %2, %1
mov %1, %2
%endm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%define TT0 ymm0
%define TT1 ymm1
%define TT2 ymm2
%define TT3 ymm3
%define TT4 ymm4
%define TT5 ymm5
%define TT6 ymm6
%define TT7 ymm7
%define TTMP1 ymm8
%define TTMP2 ymm9
%define TTMP3 ymm10
%define TTMP4 ymm11
%define TTMP5 ymm12
%ifdef LINUX
%define INP rdi ; 1st arg
%define CTX rsi ; 2nd arg
%define NUM_BLKS rdx ; 3rd arg
%define c ecx
%define d r8d
%define e edx ; dword version of NUM_BLKS
%define z3 edi ; dword version of INP
%else
%define INP rcx ; 1st arg
%define CTX rdx ; 2nd arg
%define NUM_BLKS r8 ; 3rd arg
%define c edi
%define d esi
%define e r8d ; dword version of NUM_BLKS
%define z3 ecx ; dword version of INP
%endif
%define IDX rbp
%define TBL CTX
%define a eax
%define b ebx
%define f r9d
%define g r10d
%define h r11d
%xdefine old_h h
%define T1 r12d
%define z0 r13d
%define z1 r14d
%define z1q r14
%define z2 r15d
_EXTRA_SIZE equ 32
_KTMSG_SIZE equ 16*32 ; Second 3/4 of KTMSG overlaps TMSG
_TMSG_SIZE equ 64*32
%ifdef LINUX
_XMM_SAVE_SIZE equ 0
%else
_XMM_SAVE_SIZE equ 7*16
%endif
_INP_END_SIZE equ 8
_INP_SIZE equ 8
_RND_SIZE equ 8
_CTX_SIZE equ 8
_IDX_LIMIT_SIZE equ 8
_RSP_SIZE equ 8
;; KTMSG must overlap TMSG such that the second 3/4 of KTMSG overlaps the
;; first 3/4 of TMSG. (We onl need 16 words of TMSG at any time.)
_KTMSG equ _EXTRA_SIZE
_TMSG equ _KTMSG + _KTMSG_SIZE
_XMM_SAVE equ _TMSG + _TMSG_SIZE
_INP_END equ _XMM_SAVE + _XMM_SAVE_SIZE
_INP equ _INP_END + _INP_END_SIZE
_RND equ _INP + _INP_SIZE
_CTX equ _RND + _RND_SIZE
_IDX_LIMIT equ _CTX + _CTX_SIZE
_RSP equ _IDX_LIMIT + _IDX_LIMIT_SIZE
STACK_SIZE equ _RSP + _RSP_SIZE
%macro ROTATE_ARGS 0
%xdefine old_h h
%xdefine TMP_ h
%xdefine h g
%xdefine g f
%xdefine f e
%xdefine e d
%xdefine d c
%xdefine c b
%xdefine b a
%xdefine a TMP_
%endm
; PRORD reg, imm, tmp
%macro PRORD 3
%define %%reg %1
%define %%imm %2
%define %%tmp %3
vpslld %%tmp, %%reg, (32-(%%imm))
vpsrld %%reg, %%reg, %%imm
vpor %%reg, %%reg, %%tmp
%endmacro
; non-destructive
; PRORD_nd reg, imm, tmp, src
%macro PRORD_nd 4
%define %%reg %1
%define %%imm %2
%define %%tmp %3
%define %%src %4
vpslld %%tmp, %%src, (32-(%%imm))
vpsrld %%reg, %%src, %%imm
vpor %%reg, %%reg, %%tmp
%endmacro
; PRORD dst/src, amt
%macro PRORD 2
PRORD %1, %2, TTMP5
%endmacro
; PRORD_nd dst, src, amt
%macro PRORD_nd 3
PRORD_nd %1, %3, TTMP5, %2
%endmacro
; TRANSPOSE8 r0, r1, r2, r3, r4, r5, r6, r7, t0, t1
; "transpose" data in {r0...r7} using temps {t0...t1}
; Input looks like: {r0 r1 r2 r3 r4 r5 r6 r7}
; r0 = {a7 a6 a5 a4 a3 a2 a1 a0}
; r1 = {b7 b6 b5 b4 b3 b2 b1 b0}
; r2 = {c7 c6 c5 c4 c3 c2 c1 c0}
; r3 = {d7 d6 d5 d4 d3 d2 d1 d0}
; r4 = {e7 e6 e5 e4 e3 e2 e1 e0}
; r5 = {f7 f6 f5 f4 f3 f2 f1 f0}
; r6 = {g7 g6 g5 g4 g3 g2 g1 g0}
; r7 = {h7 h6 h5 h4 h3 h2 h1 h0}
;
; Output looks like: {r0 r1 r2 r3 r4 r5 r6 r7}
; r0 = {h0 g0 f0 e0 d0 c0 b0 a0}
; r1 = {h1 g1 f1 e1 d1 c1 b1 a1}
; r2 = {h2 g2 f2 e2 d2 c2 b2 a2}
; r3 = {h3 g3 f3 e3 d3 c3 b3 a3}
; r4 = {h4 g4 f4 e4 d4 c4 b4 a4}
; r5 = {h5 g5 f5 e5 d5 c5 b5 a5}
; r6 = {h6 g6 f6 e6 d6 c6 b6 a6}
; r7 = {h7 g7 f7 e7 d7 c7 b7 a7}
;
%macro TRANSPOSE8 10
%define %%r0 %1
%define %%r1 %2
%define %%r2 %3
%define %%r3 %4
%define %%r4 %5
%define %%r5 %6
%define %%r6 %7
%define %%r7 %8
%define %%t0 %9
%define %%t1 %10
; process top half (r0..r3) {a...d}
vshufps %%t0, %%r0, %%r1, 0x44 ; t0 = {b5 b4 a5 a4 b1 b0 a1 a0}
vshufps %%r0, %%r0, %%r1, 0xEE ; r0 = {b7 b6 a7 a6 b3 b2 a3 a2}
vshufps %%t1, %%r2, %%r3, 0x44 ; t1 = {d5 d4 c5 c4 d1 d0 c1 c0}
vshufps %%r2, %%r2, %%r3, 0xEE ; r2 = {d7 d6 c7 c6 d3 d2 c3 c2}
vshufps %%r3, %%t0, %%t1, 0xDD ; r3 = {d5 c5 b5 a5 d1 c1 b1 a1}
vshufps %%r1, %%r0, %%r2, 0x88 ; r1 = {d6 c6 b6 a6 d2 c2 b2 a2}
vshufps %%r0, %%r0, %%r2, 0xDD ; r0 = {d7 c7 b7 a7 d3 c3 b3 a3}
vshufps %%t0, %%t0, %%t1, 0x88 ; t0 = {d4 c4 b4 a4 d0 c0 b0 a0}
; use r2 in place of t0
; process bottom half (r4..r7) {e...h}
vshufps %%r2, %%r4, %%r5, 0x44 ; r2 = {f5 f4 e5 e4 f1 f0 e1 e0}
vshufps %%r4, %%r4, %%r5, 0xEE ; r4 = {f7 f6 e7 e6 f3 f2 e3 e2}
vshufps %%t1, %%r6, %%r7, 0x44 ; t1 = {h5 h4 g5 g4 h1 h0 g1 g0}
vshufps %%r6, %%r6, %%r7, 0xEE ; r6 = {h7 h6 g7 g6 h3 h2 g3 g2}
vshufps %%r7, %%r2, %%t1, 0xDD ; r7 = {h5 g5 f5 e5 h1 g1 f1 e1}
vshufps %%r5, %%r4, %%r6, 0x88 ; r5 = {h6 g6 f6 e6 h2 g2 f2 e2}
vshufps %%r4, %%r4, %%r6, 0xDD ; r4 = {h7 g7 f7 e7 h3 g3 f3 e3}
vshufps %%t1, %%r2, %%t1, 0x88 ; t1 = {h4 g4 f4 e4 h0 g0 f0 e0}
vperm2f128 %%r6, %%r5, %%r1, 0x13 ; h6...a6
vperm2f128 %%r2, %%r5, %%r1, 0x02 ; h2...a2
vperm2f128 %%r5, %%r7, %%r3, 0x13 ; h5...a5
vperm2f128 %%r1, %%r7, %%r3, 0x02 ; h1...a1
vperm2f128 %%r7, %%r4, %%r0, 0x13 ; h7...a7
vperm2f128 %%r3, %%r4, %%r0, 0x02 ; h3...a3
vperm2f128 %%r4, %%t1, %%t0, 0x13 ; h4...a4
vperm2f128 %%r0, %%t1, %%t0, 0x02 ; h0...a0
%endmacro
%macro SHA256_X8MS_8RNDS 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; RND N + 0 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%assign i 0
vmovdqa TT0, [rsp + _TMSG + IDX + 32*(i+1)] ;; TT0 = Load W[i-15]
vmovdqa TTMP2,[rsp + _TMSG + IDX + 32*(i+14)] ;; TTMP2 = Load W[i-2]
mov z2, f ; z2 = f ; CH
rorx z0, e, 25 ; z0 = e >> 25 ; S1A
rorx z1, e, 11 ; z1 = e >> 11 ; S1B
xor z2, g ; z2 = f^g ; CH
PRORD_nd TTMP1,TT0,7 ;; TTMP1 = W[i-15] ror 7
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ; S1
rorx z1, e, 6 ; z1 = (e >> 6) ; S1
and z2, e ; z2 = (f^g)&e ; CH
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ^ (e>>6) ; S1
rorx T1, a, 13 ; T1 = a >> 13 ; S0B
xor z2, g ; z2 = CH = ((f^g)&e)^g ; CH
rorx z1, a, 22 ; z1 = a >> 22 ; S0A
mov z3, a ; z3 = a ; MAJA
vpsrld TT0,TT0,3 ;; TT0 = W[i-15] shr 3
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ; S0
rorx T1, a, 2 ; T1 = (a >> 2) ; S0
add h, dword[rsp + _KTMSG + IDX + 32*0] ; h = k + w + h
or z3, c ; z3 = a|c ; MAJA
vpxor TT0,TT0,TTMP1 ;; TT0 = (W[i-15] ror 7) xor (W[i-15] shr 3)
PRORD TTMP1,18-7 ;; TTMP1 = W[i-15] ror 18
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ^ (a>>2) ; S0
mov T1, a ; T1 = a ; MAJB
and z3, b ; z3 = (a|c)&b ; MAJA
and T1, c ; T1 = a&c ; MAJB
add z2, z0 ; z2 = S1 + CH ; --
vpxor TT0,TTMP1,TT0 ;; TT0 = s0
PRORD_nd TTMP1,TTMP2,17 ;; TTMP1 = W[i-2] ror 17
vpsrld TTMP2,TTMP2,10 ;; TTMP2 = W[i-2] shr 25
vpxor TTMP2,TTMP1,TTMP2 ;; TTMP2 = (W[i-2] ror 17) xor (W[i-2] shr 25)
add d, h ; d = k + w + h + d ; --
or z3, T1 ; z3 = MAJ = (a|c)&b)|(a&c) ; MAJ
add h, z1 ; h = k + w + h + S0 ; --
add d, z2 ; d = k + w + h + d + S1 + CH = d + t1 ; --
PRORD TTMP1,19-17 ;; TTMP1 = W[i-2] ror 19
vpxor TTMP1,TTMP1,TTMP2 ;; TTMP1 = s1
vpaddd TT0,TT0,TTMP1 ;; TT0 = s0 + s1
vpaddd TT0,TT0,[rsp + _TMSG + IDX + 32*(i+9)] ;; add W[i-7]
vpaddd TT0,TT0,[rsp + _TMSG + IDX + 32*(i+0)] ;; add W[i-16]
vmovdqa [rsp + _TMSG + IDX + 16*32 + i*32], TT0 ;; Save TT0 to stack
vpaddd TT0, TT0, [TBL + IDX + (i+16)*32]
vmovdqa [rsp + _KTMSG + IDX + 16*32 + i*32], TT0 ;; Save TT0 to stack
;add h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
;add h, z3 ; h = t1 + S0 + MAJ ; --
ROTATE_ARGS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; RND N + 1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%assign i (i+1)
vmovdqa TT1, [rsp + _TMSG + IDX + 32*(i+1)] ;; TT1 = Load W[i-15]
vmovdqa TTMP4,[rsp + _TMSG + IDX + 32*(i+14)] ;; TTMP4 = Load W[i-2]
add old_h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
mov z2, f ; z2 = f ; CH
rorx z0, e, 25 ; z0 = e >> 25 ; S1A
rorx z1, e, 11 ; z1 = e >> 11 ; S1B
xor z2, g ; z2 = f^g ; CH
PRORD_nd TTMP3,TT1,7 ;; TTMP3 = W[i-15] ror 7
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ; S1
rorx z1, e, 6 ; z1 = (e >> 6) ; S1
and z2, e ; z2 = (f^g)&e ; CH
add old_h, z3 ; h = t1 + S0 + MAJ ; --
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ^ (e>>6) ; S1
rorx T1, a, 13 ; T1 = a >> 13 ; S0B
xor z2, g ; z2 = CH = ((f^g)&e)^g ; CH
rorx z1, a, 22 ; z1 = a >> 22 ; S0A
mov z3, a ; z3 = a ; MAJA
vpsrld TT1,TT1,3 ;; TT1 = W[i-15] shr 3
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ; S0
rorx T1, a, 2 ; T1 = (a >> 2) ; S0
add h, dword[rsp + _KTMSG + IDX + 32*1] ; h = k + w + h
or z3, c ; z3 = a|c ; MAJA
vpxor TT1,TT1,TTMP3 ;; TT1 = (W[i-15] ror 7) xor (W[i-15] shr 3)
PRORD TTMP3,18-7 ;; TTMP3 = W[i-15] ror 18
vpxor TT1,TTMP3,TT1 ;; TT1 = s0
PRORD_nd TTMP3,TTMP4,17 ;; TTMP3 = W[i-2] ror 17
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ^ (a>>2) ; S0
mov T1, a ; T1 = a ; MAJB
and z3, b ; z3 = (a|c)&b ; MAJA
and T1, c ; T1 = a&c ; MAJB
add z2, z0 ; z2 = S1 + CH ; --
vpsrld TTMP4,TTMP4,10 ;; TTMP4 = W[i-2] shr 25
vpxor TTMP4,TTMP3,TTMP4 ;; TTMP4 = (W[i-2] ror 17) xor (W[i-2] shr 25)
PRORD TTMP3,19-17 ;; TTMP3 = W[i-2] ror 19
vpxor TTMP3,TTMP3,TTMP4 ;; TTMP3 = s1
add d, h ; d = k + w + h + d ; --
or z3, T1 ; z3 = MAJ = (a|c)&b)|(a&c) ; MAJ
add h, z1 ; h = k + w + h + S0 ; --
add d, z2 ; d = k + w + h + d + S1 + CH = d + t1 ; --
vpaddd TT1,TT1,TTMP3 ;; TT1 = s0 + s1
vpaddd TT1,TT1,[rsp + _TMSG + IDX + 32*(i+9)] ;; add W[i-7]
vpaddd TT1,TT1,[rsp + _TMSG + IDX + 32*(i+0)] ;; add W[i-16]
vmovdqa [rsp + _TMSG + IDX + 16*32 + i*32], TT1 ;; Save TT1 to stack
vpaddd TT1, TT1, [TBL + IDX + (i+16)*32]
vmovdqa [rsp + _KTMSG + IDX + 16*32 + i*32], TT1 ;; Save TT1 to stack
;add h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
;add h, z3 ; h = t1 + S0 + MAJ ; --
ROTATE_ARGS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; RND N + 2 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%assign i (i+1)
vmovdqa TT2, [rsp + _TMSG + IDX + 32*(i+1)] ;; TT2 = Load W[i-15]
vmovdqa TTMP2,[rsp + _TMSG + IDX + 32*(i+14)] ;; TTMP2 = Load W[i-2]
add old_h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
mov z2, f ; z2 = f ; CH
rorx z0, e, 25 ; z0 = e >> 25 ; S1A
rorx z1, e, 11 ; z1 = e >> 11 ; S1B
xor z2, g ; z2 = f^g ; CH
PRORD_nd TTMP1,TT2,7 ;; TTMP1 = W[i-15] ror 7
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ; S1
rorx z1, e, 6 ; z1 = (e >> 6) ; S1
and z2, e ; z2 = (f^g)&e ; CH
add old_h, z3 ; h = t1 + S0 + MAJ ; --
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ^ (e>>6) ; S1
rorx T1, a, 13 ; T1 = a >> 13 ; S0B
xor z2, g ; z2 = CH = ((f^g)&e)^g ; CH
rorx z1, a, 22 ; z1 = a >> 22 ; S0A
mov z3, a ; z3 = a ; MAJA
vpsrld TT2,TT2,3 ;; TT2 = W[i-15] shr 3
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ; S0
rorx T1, a, 2 ; T1 = (a >> 2) ; S0
add h, dword[rsp + _KTMSG + IDX + 32*2] ; h = k + w + h
or z3, c ; z3 = a|c ; MAJA
vpxor TT2,TT2,TTMP1 ;; TT2 = (W[i-15] ror 7) xor (W[i-15] shr 3)
PRORD TTMP1,18-7 ;; TTMP1 = W[i-15] ror 18
vpxor TT2,TTMP1,TT2 ;; TT2 = s0
PRORD_nd TTMP1,TTMP2,17 ;; TTMP1 = W[i-2] ror 17
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ^ (a>>2) ; S0
mov T1, a ; T1 = a ; MAJB
and z3, b ; z3 = (a|c)&b ; MAJA
and T1, c ; T1 = a&c ; MAJB
add z2, z0 ; z2 = S1 + CH ; --
vpsrld TTMP2,TTMP2,10 ;; TTMP2 = W[i-2] shr 25
vpxor TTMP2,TTMP1,TTMP2 ;; TTMP2 = (W[i-2] ror 17) xor (W[i-2] shr 25)
PRORD TTMP1,19-17 ;; TTMP1 = W[i-2] ror 19
vpxor TTMP1,TTMP1,TTMP2 ;; TTMP1 = s1
add d, h ; d = k + w + h + d ; --
or z3, T1 ; z3 = MAJ = (a|c)&b)|(a&c) ; MAJ
add h, z1 ; h = k + w + h + S0 ; --
vpaddd TT2,TT2,TTMP1 ;; TT2 = s0 + s1
vpaddd TT2,TT2,[rsp + _TMSG + IDX + 32*(i+9)] ;; add W[i-7]
vpaddd TT2,TT2,[rsp + _TMSG + IDX + 32*(i+0)] ;; add W[i-16]
vmovdqa [rsp + _TMSG + IDX + 16*32 + i*32], TT2 ;; Save TT2 to stack
vpaddd TT2, TT2, [TBL + IDX + (i+16)*32]
vmovdqa [rsp + _KTMSG + IDX + 16*32 + i*32], TT2 ;; Save TT2 to stack
add d, z2 ; d = k + w + h + d + S1 + CH = d + t1 ; --
;add h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
;add h, z3 ; h = t1 + S0 + MAJ ; --
ROTATE_ARGS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; RND N + 3 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%assign i (i+1)
vmovdqa TT3, [rsp + _TMSG + IDX + 32*(i+1)] ;; TT3 = Load W[i-15]
vmovdqa TTMP4,[rsp + _TMSG + IDX + 32*(i+14)] ;; TTMP4 = Load W[i-2]
add old_h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
mov z2, f ; z2 = f ; CH
rorx z0, e, 25 ; z0 = e >> 25 ; S1A
rorx z1, e, 11 ; z1 = e >> 11 ; S1B
xor z2, g ; z2 = f^g ; CH
PRORD_nd TTMP3,TT3,7 ;; TTMP3 = W[i-15] ror 7
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ; S1
rorx z1, e, 6 ; z1 = (e >> 6) ; S1
and z2, e ; z2 = (f^g)&e ; CH
add old_h, z3 ; h = t1 + S0 + MAJ ; --
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ^ (e>>6) ; S1
rorx T1, a, 13 ; T1 = a >> 13 ; S0B
xor z2, g ; z2 = CH = ((f^g)&e)^g ; CH
rorx z1, a, 22 ; z1 = a >> 22 ; S0A
mov z3, a ; z3 = a ; MAJA
vpsrld TT3,TT3,3 ;; TT3 = W[i-15] shr 3
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ; S0
rorx T1, a, 2 ; T1 = (a >> 2) ; S0
add h, dword[rsp + _KTMSG + IDX + 32*3] ; h = k + w + h
or z3, c ; z3 = a|c ; MAJA
vpxor TT3,TT3,TTMP3 ;; TT3 = (W[i-15] ror 7) xor (W[i-15] shr 3)
PRORD TTMP3,18-7 ;; TTMP3 = W[i-15] ror 18
vpxor TT3,TTMP3,TT3 ;; TT3 = s0
PRORD_nd TTMP3,TTMP4,17 ;; TTMP3 = W[i-2] ror 17
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ^ (a>>2) ; S0
mov T1, a ; T1 = a ; MAJB
and z3, b ; z3 = (a|c)&b ; MAJA
and T1, c ; T1 = a&c ; MAJB
add z2, z0 ; z2 = S1 + CH ; --
vpsrld TTMP4,TTMP4,10 ;; TTMP4 = W[i-2] shr 25
vpxor TTMP4,TTMP3,TTMP4 ;; TTMP4 = (W[i-2] ror 17) xor (W[i-2] shr 25)
PRORD TTMP3,19-17 ;; TTMP3 = W[i-2] ror 19
vpxor TTMP3,TTMP3,TTMP4 ;; TTMP3 = s1
add d, h ; d = k + w + h + d ; --
or z3, T1 ; z3 = MAJ = (a|c)&b)|(a&c) ; MAJ
add h, z1 ; h = k + w + h + S0 ; --
vpaddd TT3,TT3,TTMP3 ;; TT3 = s0 + s1
add d, z2 ; d = k + w + h + d + S1 + CH = d + t1 ; --
add h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
vpaddd TT3,TT3,[rsp + _TMSG + IDX + 32*(i+9)] ;; add W[i-7]
vpaddd TT3,TT3,[rsp + _TMSG + IDX + 32*(i+0)] ;; add W[i-16]
vmovdqa [rsp + _TMSG + IDX + 16*32 + i*32], TT3 ;; Save TT3 to stack
vpaddd TT3, TT3, [TBL + IDX + (i+16)*32]
vmovdqa [rsp + _KTMSG + IDX + 16*32 + i*32], TT3 ;; Save TT3 to stack
add h, z3 ; h = t1 + S0 + MAJ ; --
ROTATE_ARGS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; RND N + 4 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%assign i (i+1)
vmovdqa TT4, [rsp + _TMSG + IDX + 32*(i+1)] ;; TT4 = Load W[i-15]
vmovdqa TTMP2,[rsp + _TMSG + IDX + 32*(i+14)] ;; TTMP2 = Load W[i-2]
mov z2, f ; z2 = f ; CH
rorx z0, e, 25 ; z0 = e >> 25 ; S1A
rorx z1, e, 11 ; z1 = e >> 11 ; S1B
xor z2, g ; z2 = f^g ; CH
PRORD_nd TTMP1,TT4,7 ;; TTMP1 = W[i-15] ror 7
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ; S1
rorx z1, e, 6 ; z1 = (e >> 6) ; S1
and z2, e ; z2 = (f^g)&e ; CH
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ^ (e>>6) ; S1
rorx T1, a, 13 ; T1 = a >> 13 ; S0B
xor z2, g ; z2 = CH = ((f^g)&e)^g ; CH
rorx z1, a, 22 ; z1 = a >> 22 ; S0A
mov z3, a ; z3 = a ; MAJA
vpsrld TT4,TT4,3 ;; TT4 = W[i-15] shr 3
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ; S0
rorx T1, a, 2 ; T1 = (a >> 2) ; S0
add h, dword[rsp + _KTMSG + IDX + 32*4] ; h = k + w + h
or z3, c ; z3 = a|c ; MAJA
vpxor TT4,TT4,TTMP1 ;; TT4 = (W[i-15] ror 7) xor (W[i-15] shr 3)
PRORD TTMP1,18-7 ;; TTMP1 = W[i-15] ror 18
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ^ (a>>2) ; S0
mov T1, a ; T1 = a ; MAJB
and z3, b ; z3 = (a|c)&b ; MAJA
and T1, c ; T1 = a&c ; MAJB
add z2, z0 ; z2 = S1 + CH ; --
vpxor TT4,TTMP1,TT4 ;; TT4 = s0
PRORD_nd TTMP1,TTMP2,17 ;; TTMP1 = W[i-2] ror 17
vpsrld TTMP2,TTMP2,10 ;; TTMP2 = W[i-2] shr 25
vpxor TTMP2,TTMP1,TTMP2 ;; TTMP2 = (W[i-2] ror 17) xor (W[i-2] shr 25)
add d, h ; d = k + w + h + d ; --
or z3, T1 ; z3 = MAJ = (a|c)&b)|(a&c) ; MAJ
add h, z1 ; h = k + w + h + S0 ; --
PRORD TTMP1,19-17 ;; TTMP1 = W[i-2] ror 19
vpxor TTMP1,TTMP1,TTMP2 ;; TTMP1 = s1
vpaddd TT4,TT4,TTMP1 ;; TT4 = s0 + s1
add d, z2 ; d = k + w + h + d + S1 + CH = d + t1 ; --
;add h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
;add h, z3 ; h = t1 + S0 + MAJ ; --
vpaddd TT4,TT4,[rsp + _TMSG + IDX + 32*(i+9)] ;; add W[i-7]
vpaddd TT4,TT4,[rsp + _TMSG + IDX + 32*(i+0)] ;; add W[i-16]
vmovdqa [rsp + _TMSG + IDX + 16*32 + i*32], TT4 ;; Save TT4 to stack
vpaddd TT4, TT4, [TBL + IDX + (i+16)*32]
vmovdqa [rsp + _KTMSG + IDX + 16*32 + i*32], TT4 ;; Save TT4 to stack
ROTATE_ARGS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; RND N + 5 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%assign i (i+1)
vmovdqa TT5, [rsp + _TMSG + IDX + 32*(i+1)] ;; TT5 = Load W[i-15]
vmovdqa TTMP4,[rsp + _TMSG + IDX + 32*(i+14)] ;; TTMP4 = Load W[i-2]
add old_h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
mov z2, f ; z2 = f ; CH
rorx z0, e, 25 ; z0 = e >> 25 ; S1A
rorx z1, e, 11 ; z1 = e >> 11 ; S1B
xor z2, g ; z2 = f^g ; CH
PRORD_nd TTMP3,TT5,7 ;; TTMP3 = W[i-15] ror 7
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ; S1
rorx z1, e, 6 ; z1 = (e >> 6) ; S1
and z2, e ; z2 = (f^g)&e ; CH
add old_h, z3 ; h = t1 + S0 + MAJ ; --
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ^ (e>>6) ; S1
rorx T1, a, 13 ; T1 = a >> 13 ; S0B
xor z2, g ; z2 = CH = ((f^g)&e)^g ; CH
rorx z1, a, 22 ; z1 = a >> 22 ; S0A
mov z3, a ; z3 = a ; MAJA
vpsrld TT5,TT5,3 ;; TT5 = W[i-15] shr 3
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ; S0
rorx T1, a, 2 ; T1 = (a >> 2) ; S0
add h, dword[rsp + _KTMSG + IDX + 32*5] ; h = k + w + h
or z3, c ; z3 = a|c ; MAJA
vpxor TT5,TT5,TTMP3 ;; TT5 = (W[i-15] ror 7) xor (W[i-15] shr 3)
PRORD TTMP3,18-7 ;; TTMP3 = W[i-15] ror 18
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ^ (a>>2) ; S0
mov T1, a ; T1 = a ; MAJB
and z3, b ; z3 = (a|c)&b ; MAJA
and T1, c ; T1 = a&c ; MAJB
add z2, z0 ; z2 = S1 + CH ; --
vpxor TT5,TTMP3,TT5 ;; TT5 = s0
PRORD_nd TTMP3,TTMP4,17 ;; TTMP3 = W[i-2] ror 17
vpsrld TTMP4,TTMP4,10 ;; TTMP4 = W[i-2] shr 25
vpxor TTMP4,TTMP3,TTMP4 ;; TTMP4 = (W[i-2] ror 17) xor (W[i-2] shr 25)
add d, h ; d = k + w + h + d ; --
or z3, T1 ; z3 = MAJ = (a|c)&b)|(a&c) ; MAJ
add h, z1 ; h = k + w + h + S0 ; --
PRORD TTMP3,19-17 ;; TTMP3 = W[i-2] ror 19
vpxor TTMP3,TTMP3,TTMP4 ;; TTMP3 = s1
vpaddd TT5,TT5,TTMP3 ;; TT5 = s0 + s1
add d, z2 ; d = k + w + h + d + S1 + CH = d + t1 ; --
;add h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
;add h, z3 ; h = t1 + S0 + MAJ ; --
vpaddd TT5,TT5,[rsp + _TMSG + IDX + 32*(i+9)] ;; add W[i-7]
vpaddd TT5,TT5,[rsp + _TMSG + IDX + 32*(i+0)] ;; add W[i-16]
vmovdqa [rsp + _TMSG + IDX + 16*32 + i*32], TT5 ;; Save TT5 to stack
vpaddd TT5, TT5, [TBL + IDX + (i+16)*32]
vmovdqa [rsp + _KTMSG + IDX + 16*32 + i*32], TT5 ;; Save TT5 to stack
ROTATE_ARGS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; RND N + 6 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%assign i (i+1)
vmovdqa TT6, [rsp + _TMSG + IDX + 32*(i+1)] ;; TT6 = Load W[i-15]
vmovdqa TTMP2,[rsp + _TMSG + IDX + 32*(i+14)] ;; TTMP2 = Load W[i-2]
add old_h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
mov z2, f ; z2 = f ; CH
rorx z0, e, 25 ; z0 = e >> 25 ; S1A
rorx z1, e, 11 ; z1 = e >> 11 ; S1B
xor z2, g ; z2 = f^g ; CH
PRORD_nd TTMP1,TT6,7 ;; TTMP1 = W[i-15] ror 7
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ; S1
rorx z1, e, 6 ; z1 = (e >> 6) ; S1
and z2, e ; z2 = (f^g)&e ; CH
add old_h, z3 ; h = t1 + S0 + MAJ ; --
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ^ (e>>6) ; S1
rorx T1, a, 13 ; T1 = a >> 13 ; S0B
xor z2, g ; z2 = CH = ((f^g)&e)^g ; CH
rorx z1, a, 22 ; z1 = a >> 22 ; S0A
mov z3, a ; z3 = a ; MAJA
vpsrld TT6,TT6,3 ;; TT6 = W[i-15] shr 3
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ; S0
rorx T1, a, 2 ; T1 = (a >> 2) ; S0
add h, dword[rsp + _KTMSG + IDX + 32*6] ; h = k + w + h
or z3, c ; z3 = a|c ; MAJA
vpxor TT6,TT6,TTMP1 ;; TT6 = (W[i-15] ror 7) xor (W[i-15] shr 3)
PRORD TTMP1,18-7 ;; TTMP1 = W[i-15] ror 18
vpxor TT6,TTMP1,TT6 ;; TT6 = s0
PRORD_nd TTMP1,TTMP2,17 ;; TTMP1 = W[i-2] ror 17
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ^ (a>>2) ; S0
mov T1, a ; T1 = a ; MAJB
and z3, b ; z3 = (a|c)&b ; MAJA
and T1, c ; T1 = a&c ; MAJB
add z2, z0 ; z2 = S1 + CH ; --
vpsrld TTMP2,TTMP2,10 ;; TTMP2 = W[i-2] shr 25
vpxor TTMP2,TTMP1,TTMP2 ;; TTMP2 = (W[i-2] ror 17) xor (W[i-2] shr 25)
PRORD TTMP1,19-17 ;; TTMP1 = W[i-2] ror 19
vpxor TTMP1,TTMP1,TTMP2 ;; TTMP1 = s1
add d, h ; d = k + w + h + d ; --
or z3, T1 ; z3 = MAJ = (a|c)&b)|(a&c) ; MAJ
add h, z1 ; h = k + w + h + S0 ; --
vpaddd TT6,TT6,TTMP1 ;; TT6 = s0 + s1
vpaddd TT6,TT6,[rsp + _TMSG + IDX + 32*(i+9)] ;; add W[i-7]
add d, z2 ; d = k + w + h + d + S1 + CH = d + t1 ; --
;add h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
;add h, z3 ; h = t1 + S0 + MAJ ; --
vpaddd TT6,TT6,[rsp + _TMSG + IDX + 32*(i+0)] ;; add W[i-16]
vmovdqa [rsp + _TMSG + IDX + 16*32 + i*32], TT6 ;; Save TT6 to stack
vpaddd TT6, TT6, [TBL + IDX + (i+16)*32]
vmovdqa [rsp + _KTMSG + IDX + 16*32 + i*32], TT6 ;; Save TT6 to stack
ROTATE_ARGS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; RND N + 7 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%assign i (i+1)
vmovdqa TT7, [rsp + _TMSG + IDX + 32*(i+1)] ;; TT7 = Load W[i-15]
vmovdqa TTMP4,[rsp + _TMSG + IDX + 32*(i+14)] ;; TTMP4 = Load W[i-2]
add old_h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
mov z2, f ; z2 = f ; CH
rorx z0, e, 25 ; z0 = e >> 25 ; S1A
rorx z1, e, 11 ; z1 = e >> 11 ; S1B
xor z2, g ; z2 = f^g ; CH
PRORD_nd TTMP3,TT7,7 ;; TTMP3 = W[i-15] ror 7
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ; S1
rorx z1, e, 6 ; z1 = (e >> 6) ; S1
and z2, e ; z2 = (f^g)&e ; CH
add old_h, z3 ; h = t1 + S0 + MAJ ; --
vpsrld TT7,TT7,3 ;; TT7 = W[i-15] shr 3
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ^ (e>>6) ; S1
rorx T1, a, 13 ; T1 = a >> 13 ; S0B
xor z2, g ; z2 = CH = ((f^g)&e)^g ; CH
rorx z1, a, 22 ; z1 = a >> 22 ; S0A
mov z3, a ; z3 = a ; MAJA
vpxor TT7,TT7,TTMP3 ;; TT7 = (W[i-15] ror 7) xor (W[i-15] shr 3)
PRORD TTMP3,18-7 ;; TTMP3 = W[i-15] ror 18
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ; S0
rorx T1, a, 2 ; T1 = (a >> 2) ; S0
add h, dword[rsp + _KTMSG + IDX + 32*7] ; h = k + w + h
or z3, c ; z3 = a|c ; MAJA
vpxor TT7,TTMP3,TT7 ;; TT7 = s0
PRORD_nd TTMP3,TTMP4,17 ;; TTMP3 = W[i-2] ror 17
vpsrld TTMP4,TTMP4,10 ;; TTMP4 = W[i-2] shr 25
vpxor TTMP4,TTMP3,TTMP4 ;; TTMP4 = (W[i-2] ror 17) xor (W[i-2] shr 25)
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ^ (a>>2) ; S0
mov T1, a ; T1 = a ; MAJB
and z3, b ; z3 = (a|c)&b ; MAJA
and T1, c ; T1 = a&c ; MAJB
add z2, z0 ; z2 = S1 + CH ; --
PRORD TTMP3,19-17 ;; TTMP3 = W[i-2] ror 19
vpxor TTMP3,TTMP3,TTMP4 ;; TTMP3 = s1
add d, h ; d = k + w + h + d ; --
or z3, T1 ; z3 = MAJ = (a|c)&b)|(a&c) ; MAJ
add h, z1 ; h = k + w + h + S0 ; --
vpaddd TT7,TT7,TTMP3 ;; TT7 = s0 + s1
add d, z2 ; d = k + w + h + d + S1 + CH = d + t1 ; --
vpaddd TT7,TT7,[rsp + _TMSG + IDX + 32*(i+9)] ;; add W[i-7]
add h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
vpaddd TT7,TT7,[rsp + _TMSG + IDX + 32*(i+0)] ;; add W[i-16]
add h, z3 ; h = t1 + S0 + MAJ ; --
vmovdqa [rsp + _TMSG + IDX + 16*32 + i*32], TT7 ;; Save TT7 to stack
vpaddd TT7, TT7, [TBL + IDX + (i+16)*32]
vmovdqa [rsp + _KTMSG + IDX + 16*32 + i*32], TT7 ;; Save TT7 to stack
ROTATE_ARGS
%endm
%macro DO_8ROUNDS 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; RND N + 0 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov z2, f ; z2 = f ; CH
rorx z0, e, 25 ; z0 = e >> 25 ; S1A
rorx z1, e, 11 ; z1 = e >> 11 ; S1B
xor z2, g ; z2 = f^g ; CH
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ; S1
rorx z1, e, 6 ; z1 = (e >> 6) ; S1
and z2, e ; z2 = (f^g)&e ; CH
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ^ (e>>6) ; S1
rorx T1, a, 13 ; T1 = a >> 13 ; S0B
xor z2, g ; z2 = CH = ((f^g)&e)^g ; CH
rorx z1, a, 22 ; z1 = a >> 22 ; S0A
mov z3, a ; z3 = a ; MAJA
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ; S0
rorx T1, a, 2 ; T1 = (a >> 2) ; S0
add h, dword[rsp + _KTMSG + IDX + 32*0] ; h = k + w + h
or z3, c ; z3 = a|c ; MAJA
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ^ (a>>2) ; S0
mov T1, a ; T1 = a ; MAJB
and z3, b ; z3 = (a|c)&b ; MAJA
and T1, c ; T1 = a&c ; MAJB
add z2, z0 ; z2 = S1 + CH ; --
add d, h ; d = k + w + h + d ; --
or z3, T1 ; z3 = MAJ = (a|c)&b)|(a&c) ; MAJ
add h, z1 ; h = k + w + h + S0 ; --
add d, z2 ; d = k + w + h + d + S1 + CH = d + t1 ; --
;add h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
;add h, z3 ; h = t1 + S0 + MAJ ; --
ROTATE_ARGS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; RND N + 1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
add old_h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
mov z2, f ; z2 = f ; CH
rorx z0, e, 25 ; z0 = e >> 25 ; S1A
rorx z1, e, 11 ; z1 = e >> 11 ; S1B
xor z2, g ; z2 = f^g ; CH
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ; S1
rorx z1, e, 6 ; z1 = (e >> 6) ; S1
and z2, e ; z2 = (f^g)&e ; CH
add old_h, z3 ; h = t1 + S0 + MAJ ; --
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ^ (e>>6) ; S1
rorx T1, a, 13 ; T1 = a >> 13 ; S0B
xor z2, g ; z2 = CH = ((f^g)&e)^g ; CH
rorx z1, a, 22 ; z1 = a >> 22 ; S0A
mov z3, a ; z3 = a ; MAJA
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ; S0
rorx T1, a, 2 ; T1 = (a >> 2) ; S0
add h, dword[rsp + _KTMSG + IDX + 32*1] ; h = k + w + h
or z3, c ; z3 = a|c ; MAJA
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ^ (a>>2) ; S0
mov T1, a ; T1 = a ; MAJB
and z3, b ; z3 = (a|c)&b ; MAJA
and T1, c ; T1 = a&c ; MAJB
add z2, z0 ; z2 = S1 + CH ; --
add d, h ; d = k + w + h + d ; --
or z3, T1 ; z3 = MAJ = (a|c)&b)|(a&c) ; MAJ
add h, z1 ; h = k + w + h + S0 ; --
add d, z2 ; d = k + w + h + d + S1 + CH = d + t1 ; --
;add h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
;add h, z3 ; h = t1 + S0 + MAJ ; --
ROTATE_ARGS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; RND N + 2 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
add old_h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
mov z2, f ; z2 = f ; CH
rorx z0, e, 25 ; z0 = e >> 25 ; S1A
rorx z1, e, 11 ; z1 = e >> 11 ; S1B
xor z2, g ; z2 = f^g ; CH
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ; S1
rorx z1, e, 6 ; z1 = (e >> 6) ; S1
and z2, e ; z2 = (f^g)&e ; CH
add old_h, z3 ; h = t1 + S0 + MAJ ; --
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ^ (e>>6) ; S1
rorx T1, a, 13 ; T1 = a >> 13 ; S0B
xor z2, g ; z2 = CH = ((f^g)&e)^g ; CH
rorx z1, a, 22 ; z1 = a >> 22 ; S0A
mov z3, a ; z3 = a ; MAJA
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ; S0
rorx T1, a, 2 ; T1 = (a >> 2) ; S0
add h, dword[rsp + _KTMSG + IDX + 32*2] ; h = k + w + h
or z3, c ; z3 = a|c ; MAJA
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ^ (a>>2) ; S0
mov T1, a ; T1 = a ; MAJB
and z3, b ; z3 = (a|c)&b ; MAJA
and T1, c ; T1 = a&c ; MAJB
add z2, z0 ; z2 = S1 + CH ; --
add d, h ; d = k + w + h + d ; --
or z3, T1 ; z3 = MAJ = (a|c)&b)|(a&c) ; MAJ
add h, z1 ; h = k + w + h + S0 ; --
add d, z2 ; d = k + w + h + d + S1 + CH = d + t1 ; --
;add h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
;add h, z3 ; h = t1 + S0 + MAJ ; --
ROTATE_ARGS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; RND N + 3 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
add old_h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
mov z2, f ; z2 = f ; CH
rorx z0, e, 25 ; z0 = e >> 25 ; S1A
rorx z1, e, 11 ; z1 = e >> 11 ; S1B
xor z2, g ; z2 = f^g ; CH
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ; S1
rorx z1, e, 6 ; z1 = (e >> 6) ; S1
and z2, e ; z2 = (f^g)&e ; CH
add old_h, z3 ; h = t1 + S0 + MAJ ; --
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ^ (e>>6) ; S1
rorx T1, a, 13 ; T1 = a >> 13 ; S0B
xor z2, g ; z2 = CH = ((f^g)&e)^g ; CH
rorx z1, a, 22 ; z1 = a >> 22 ; S0A
mov z3, a ; z3 = a ; MAJA
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ; S0
rorx T1, a, 2 ; T1 = (a >> 2) ; S0
add h, dword[rsp + _KTMSG + IDX + 32*3] ; h = k + w + h
or z3, c ; z3 = a|c ; MAJA
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ^ (a>>2) ; S0
mov T1, a ; T1 = a ; MAJB
and z3, b ; z3 = (a|c)&b ; MAJA
and T1, c ; T1 = a&c ; MAJB
add z2, z0 ; z2 = S1 + CH ; --
add d, h ; d = k + w + h + d ; --
or z3, T1 ; z3 = MAJ = (a|c)&b)|(a&c) ; MAJ
add h, z1 ; h = k + w + h + S0 ; --
add d, z2 ; d = k + w + h + d + S1 + CH = d + t1 ; --
add h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
add h, z3 ; h = t1 + S0 + MAJ ; --
ROTATE_ARGS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; RND N + 4 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov z2, f ; z2 = f ; CH
rorx z0, e, 25 ; z0 = e >> 25 ; S1A
rorx z1, e, 11 ; z1 = e >> 11 ; S1B
xor z2, g ; z2 = f^g ; CH
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ; S1
rorx z1, e, 6 ; z1 = (e >> 6) ; S1
and z2, e ; z2 = (f^g)&e ; CH
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ^ (e>>6) ; S1
rorx T1, a, 13 ; T1 = a >> 13 ; S0B
xor z2, g ; z2 = CH = ((f^g)&e)^g ; CH
rorx z1, a, 22 ; z1 = a >> 22 ; S0A
mov z3, a ; z3 = a ; MAJA
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ; S0
rorx T1, a, 2 ; T1 = (a >> 2) ; S0
add h, dword[rsp + _KTMSG + IDX + 32*4] ; h = k + w + h
or z3, c ; z3 = a|c ; MAJA
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ^ (a>>2) ; S0
mov T1, a ; T1 = a ; MAJB
and z3, b ; z3 = (a|c)&b ; MAJA
and T1, c ; T1 = a&c ; MAJB
add z2, z0 ; z2 = S1 + CH ; --
add d, h ; d = k + w + h + d ; --
or z3, T1 ; z3 = MAJ = (a|c)&b)|(a&c) ; MAJ
add h, z1 ; h = k + w + h + S0 ; --
add d, z2 ; d = k + w + h + d + S1 + CH = d + t1 ; --
;add h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
;add h, z3 ; h = t1 + S0 + MAJ ; --
ROTATE_ARGS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; RND N + 5 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
add old_h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
mov z2, f ; z2 = f ; CH
rorx z0, e, 25 ; z0 = e >> 25 ; S1A
rorx z1, e, 11 ; z1 = e >> 11 ; S1B
xor z2, g ; z2 = f^g ; CH
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ; S1
rorx z1, e, 6 ; z1 = (e >> 6) ; S1
and z2, e ; z2 = (f^g)&e ; CH
add old_h, z3 ; h = t1 + S0 + MAJ ; --
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ^ (e>>6) ; S1
rorx T1, a, 13 ; T1 = a >> 13 ; S0B
xor z2, g ; z2 = CH = ((f^g)&e)^g ; CH
rorx z1, a, 22 ; z1 = a >> 22 ; S0A
mov z3, a ; z3 = a ; MAJA
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ; S0
rorx T1, a, 2 ; T1 = (a >> 2) ; S0
add h, dword[rsp + _KTMSG + IDX + 32*5] ; h = k + w + h
or z3, c ; z3 = a|c ; MAJA
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ^ (a>>2) ; S0
mov T1, a ; T1 = a ; MAJB
and z3, b ; z3 = (a|c)&b ; MAJA
and T1, c ; T1 = a&c ; MAJB
add z2, z0 ; z2 = S1 + CH ; --
add d, h ; d = k + w + h + d ; --
or z3, T1 ; z3 = MAJ = (a|c)&b)|(a&c) ; MAJ
add h, z1 ; h = k + w + h + S0 ; --
add d, z2 ; d = k + w + h + d + S1 + CH = d + t1 ; --
;add h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
;add h, z3 ; h = t1 + S0 + MAJ ; --
ROTATE_ARGS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; RND N + 6 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
add old_h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
mov z2, f ; z2 = f ; CH
rorx z0, e, 25 ; z0 = e >> 25 ; S1A
rorx z1, e, 11 ; z1 = e >> 11 ; S1B
xor z2, g ; z2 = f^g ; CH
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ; S1
rorx z1, e, 6 ; z1 = (e >> 6) ; S1
and z2, e ; z2 = (f^g)&e ; CH
add old_h, z3 ; h = t1 + S0 + MAJ ; --
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ^ (e>>6) ; S1
rorx T1, a, 13 ; T1 = a >> 13 ; S0B
xor z2, g ; z2 = CH = ((f^g)&e)^g ; CH
rorx z1, a, 22 ; z1 = a >> 22 ; S0A
mov z3, a ; z3 = a ; MAJA
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ; S0
rorx T1, a, 2 ; T1 = (a >> 2) ; S0
add h, dword[rsp + _KTMSG + IDX + 32*6] ; h = k + w + h
or z3, c ; z3 = a|c ; MAJA
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ^ (a>>2) ; S0
mov T1, a ; T1 = a ; MAJB
and z3, b ; z3 = (a|c)&b ; MAJA
and T1, c ; T1 = a&c ; MAJB
add z2, z0 ; z2 = S1 + CH ; --
add d, h ; d = k + w + h + d ; --
or z3, T1 ; z3 = MAJ = (a|c)&b)|(a&c) ; MAJ
add h, z1 ; h = k + w + h + S0 ; --
add d, z2 ; d = k + w + h + d + S1 + CH = d + t1 ; --
;add h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
;add h, z3 ; h = t1 + S0 + MAJ ; --
ROTATE_ARGS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; RND N + 7 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
add old_h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
mov z2, f ; z2 = f ; CH
rorx z0, e, 25 ; z0 = e >> 25 ; S1A
rorx z1, e, 11 ; z1 = e >> 11 ; S1B
xor z2, g ; z2 = f^g ; CH
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ; S1
rorx z1, e, 6 ; z1 = (e >> 6) ; S1
and z2, e ; z2 = (f^g)&e ; CH
add old_h, z3 ; h = t1 + S0 + MAJ ; --
xor z0, z1 ; z0 = (e>>25) ^ (e>>11) ^ (e>>6) ; S1
rorx T1, a, 13 ; T1 = a >> 13 ; S0B
xor z2, g ; z2 = CH = ((f^g)&e)^g ; CH
rorx z1, a, 22 ; z1 = a >> 22 ; S0A
mov z3, a ; z3 = a ; MAJA
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ; S0
rorx T1, a, 2 ; T1 = (a >> 2) ; S0
add h, dword[rsp + _KTMSG + IDX + 32*7] ; h = k + w + h
or z3, c ; z3 = a|c ; MAJA
xor z1, T1 ; z1 = (a>>22) ^ (a>>13) ^ (a>>2) ; S0
mov T1, a ; T1 = a ; MAJB
and z3, b ; z3 = (a|c)&b ; MAJA
and T1, c ; T1 = a&c ; MAJB
add z2, z0 ; z2 = S1 + CH ; --
add d, h ; d = k + w + h + d ; --
or z3, T1 ; z3 = MAJ = (a|c)&b)|(a&c) ; MAJ
add h, z1 ; h = k + w + h + S0 ; --
add d, z2 ; d = k + w + h + d + S1 + CH = d + t1 ; --
add h, z2 ; h = k + w + h + S0 + S1 + CH = t1 + S0 ; --
add h, z3 ; h = t1 + S0 + MAJ ; --
ROTATE_ARGS
%endm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; void sha256_rorx_x8ms(void *input_data, UINT32 digest[8], UINT64 num_blks)
;; arg 1 : pointer to input data
;; arg 2 : pointer to digest
;; arg 3 : Num blocks
section .text
global github_com_juanmera_lenovata_intelsha.Sha256RorxX8ms
align 32
github_com_juanmera_lenovata_intelsha.Sha256RorxX8ms:
push rbx
%ifndef LINUX
push rsi
push rdi
%endif
push rbp
push r12
push r13
push r14
push r15
mov rax, rsp
sub rsp,STACK_SIZE
and rsp,-32
mov [rsp + _RSP], rax
mov qword [rsp + _IDX_LIMIT], 32
%ifndef LINUX
vmovdqa [rsp + _XMM_SAVE + 0*16],xmm6
vmovdqa [rsp + _XMM_SAVE + 1*16],xmm7
vmovdqa [rsp + _XMM_SAVE + 2*16],xmm8
vmovdqa [rsp + _XMM_SAVE + 3*16],xmm9
vmovdqa [rsp + _XMM_SAVE + 4*16],xmm10
vmovdqa [rsp + _XMM_SAVE + 5*16],xmm11
vmovdqa [rsp + _XMM_SAVE + 6*16],xmm12
%endif
shl NUM_BLKS, 6 ; convert to bytes
jz done_hash
lea NUM_BLKS, [NUM_BLKS + INP - 8*64]
mov [rsp + _INP_END], NUM_BLKS
mov [rsp + _CTX], CTX
cmp NUM_BLKS, INP
jb less_than_8_blocks
;; load initial digest
mov a,[4*0 + CTX]
mov b,[4*1 + CTX]
mov c,[4*2 + CTX]
mov d,[4*3 + CTX]
mov e,[4*4 + CTX]
mov f,[4*5 + CTX]
mov g,[4*6 + CTX]
mov h,[4*7 + CTX]
eight_blocks_loop:
align 32
lea TBL,[K256_SIMD wrt rip]
vmovdqa TTMP3, [PSHUFFLE_BYTE_FLIP_MASK wrt rip]
;; Load 8 blocks of message and transpose and save to stack
%assign i 0
%rep 2
vmovups TT0,[INP+0*64+i*32]
vpshufb TT0, TT0, TTMP3
vmovups TT1,[INP+1*64+i*32]
vpshufb TT1, TT1, TTMP3
vmovups TT2,[INP+2*64+i*32]
vpshufb TT2, TT2, TTMP3
vmovups TT3,[INP+3*64+i*32]
vpshufb TT3, TT3, TTMP3
vmovups TT4,[INP+4*64+i*32]
vpshufb TT4, TT4, TTMP3
vmovups TT5,[INP+5*64+i*32]
vpshufb TT5, TT5, TTMP3
vmovups TT6,[INP+6*64+i*32]
vpshufb TT6, TT6, TTMP3
vmovups TT7,[INP+7*64+i*32]
vpshufb TT7, TT7, TTMP3
TRANSPOSE8 TT0, TT1, TT2, TT3, TT4, TT5, TT6, TT7, TTMP1, TTMP2
vmovdqa [rsp + _TMSG + 0*32 + i*8*32], TT0
vpaddd TT0, TT0, [TBL + 0*32 + i*8*32]
vmovdqa [rsp + _KTMSG + 0*32 + i*8*32], TT0
vmovdqa [rsp + _TMSG + 1*32 + i*8*32], TT1
vpaddd TT1, TT1, [TBL + 1*32 + i*8*32]
vmovdqa [rsp + _KTMSG + 1*32 + i*8*32], TT1
vmovdqa [rsp + _TMSG + 2*32 + i*8*32], TT2
vpaddd TT2, TT2, [TBL + 2*32 + i*8*32]
vmovdqa [rsp + _KTMSG + 2*32 + i*8*32], TT2
vmovdqa [rsp + _TMSG + 3*32 + i*8*32], TT3
vpaddd TT3, TT3, [TBL + 3*32 + i*8*32]
vmovdqa [rsp + _KTMSG + 3*32 + i*8*32], TT3
vmovdqa [rsp + _TMSG + 4*32 + i*8*32], TT4
vpaddd TT4, TT4, [TBL + 4*32 + i*8*32]
vmovdqa [rsp + _KTMSG + 4*32 + i*8*32], TT4
vmovdqa [rsp + _TMSG + 5*32 + i*8*32], TT5
vpaddd TT5, TT5, [TBL + 5*32 + i*8*32]
vmovdqa [rsp + _KTMSG + 5*32 + i*8*32], TT5
vmovdqa [rsp + _TMSG + 6*32 + i*8*32], TT6
vpaddd TT6, TT6, [TBL + 6*32 + i*8*32]
vmovdqa [rsp + _KTMSG + 6*32 + i*8*32], TT6
vmovdqa [rsp + _TMSG + 7*32 + i*8*32], TT7
vpaddd TT7, TT7, [TBL + 7*32 + i*8*32]
vmovdqa [rsp + _KTMSG + 7*32 + i*8*32], TT7
%assign i (i+1)
%endrep
after_load:
;; Save Input Msg pointer to stack
add INP, 8*64
mov [rsp + _INP], INP
;; Initialize Msg Index to Zero
xor IDX, IDX
sha256_x8ms_8rnds_loop:
;; Perform Message Scheduling of the next 8 rounds (from round 17 to 64)
;; Also perform compress function for first block from round 1 to 16.
SHA256_X8MS_8RNDS
;; Check how many rounds have been performed
add IDX, 8*32
cmp IDX, 6 * 8*32
jne sha256_x8ms_8rnds_loop
mov CTX, [rsp + _CTX]
compress_block_loop:
;; Perform 8 rounds of compression
DO_8ROUNDS
add IDX, 8*32
cmp IDX, 8 * 8*32
jb compress_block_loop
;; Update the State when block compression has been completed
addm [4*0 + CTX],a
addm [4*1 + CTX],b
addm [4*2 + CTX],c
addm [4*3 + CTX],d
addm [4*4 + CTX],e
addm [4*5 + CTX],f
addm [4*6 + CTX],g
addm [4*7 + CTX],h
sub IDX, (8 * 8*32) - 4
;; Check if the 8th block has been compressed
cmp IDX, [rsp + _IDX_LIMIT]
jne compress_block_loop
;; Check if the last set of 8 blocks has been processed
mov INP, [rsp + _INP]
cmp INP, [rsp + _INP_END]
jbe eight_blocks_loop
near_end_of_page:
mov z1q, [rsp + _INP_END]
sub z1q, INP
; z1q is minus number of NULL blocks left out of 8
cmp z1q, -(8*64)
jle done_hash
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; z1q is -1...-7 (*64) meaning we need to process 7...1 more blocks
add INP, z1q
lea TBL,[K256_SIMD wrt rip]
sar z1q, 4 ; convert to blks * 4
vmovdqa TTMP3, [PSHUFFLE_BYTE_FLIP_MASK wrt rip]
;; Load 8 blocks of message and transpose and save to stack
%assign i 0
%rep 2
vmovups TT0,[INP+0*64+i*32]
vpshufb TT0, TT0, TTMP3
vmovups TT1,[INP+1*64+i*32]
vpshufb TT1, TT1, TTMP3
vmovups TT2,[INP+2*64+i*32]
vpshufb TT2, TT2, TTMP3
vmovups TT3,[INP+3*64+i*32]
vpshufb TT3, TT3, TTMP3
vmovups TT4,[INP+4*64+i*32]
vpshufb TT4, TT4, TTMP3
vmovups TT5,[INP+5*64+i*32]
vpshufb TT5, TT5, TTMP3
vmovups TT6,[INP+6*64+i*32]
vpshufb TT6, TT6, TTMP3
vmovups TT7,[INP+7*64+i*32]
vpshufb TT7, TT7, TTMP3
TRANSPOSE8 TT0, TT1, TT2, TT3, TT4, TT5, TT6, TT7, TTMP1, TTMP2
vmovdqu [rsp + z1q + _TMSG + 0*32 + i*8*32], TT0
vpaddd TT0, TT0, [TBL + 0*32 + i*8*32]
vmovdqu [rsp + z1q + _KTMSG + 0*32 + i*8*32], TT0
vmovdqu [rsp + z1q + _TMSG + 1*32 + i*8*32], TT1
vpaddd TT1, TT1, [TBL + 1*32 + i*8*32]
vmovdqu [rsp + z1q + _KTMSG + 1*32 + i*8*32], TT1
vmovdqu [rsp + z1q + _TMSG + 2*32 + i*8*32], TT2
vpaddd TT2, TT2, [TBL + 2*32 + i*8*32]
vmovdqu [rsp + z1q + _KTMSG + 2*32 + i*8*32], TT2
vmovdqu [rsp + z1q + _TMSG + 3*32 + i*8*32], TT3
vpaddd TT3, TT3, [TBL + 3*32 + i*8*32]
vmovdqu [rsp + z1q + _KTMSG + 3*32 + i*8*32], TT3
vmovdqu [rsp + z1q + _TMSG + 4*32 + i*8*32], TT4
vpaddd TT4, TT4, [TBL + 4*32 + i*8*32]
vmovdqu [rsp + z1q + _KTMSG + 4*32 + i*8*32], TT4
vmovdqu [rsp + z1q + _TMSG + 5*32 + i*8*32], TT5
vpaddd TT5, TT5, [TBL + 5*32 + i*8*32]
vmovdqu [rsp + z1q + _KTMSG + 5*32 + i*8*32], TT5
vmovdqu [rsp + z1q + _TMSG + 6*32 + i*8*32], TT6
vpaddd TT6, TT6, [TBL + 6*32 + i*8*32]
vmovdqu [rsp + z1q + _KTMSG + 6*32 + i*8*32], TT6
vmovdqu [rsp + z1q + _TMSG + 7*32 + i*8*32], TT7
vpaddd TT7, TT7, [TBL + 7*32 + i*8*32]
vmovdqu [rsp + z1q + _KTMSG + 7*32 + i*8*32], TT7
%assign i (i+1)
%endrep
add z1q, 4*8 ; z1q = 4 * (number of blocks to proc)
mov [rsp + _IDX_LIMIT], z1q
jmp after_load
less_than_8_blocks:
;; load initial digest
mov a,[4*0 + CTX]
mov b,[4*1 + CTX]
mov c,[4*2 + CTX]
mov d,[4*3 + CTX]
mov e,[4*4 + CTX]
mov f,[4*5 + CTX]
mov g,[4*6 + CTX]
mov h,[4*7 + CTX]
mov z1q, INP
and z1q, 4095 ; offset into page
cmp z1q, 4096 - (8*64)
ja near_end_of_page
near_start_of_page:
mov z1q, [rsp + _INP_END]
sub z1q, INP
sar z1q, 4 ; convert to blks * 4
add z1q, 4*8 ; z1q = 4 * (number of blocks to proc)
mov [rsp + _IDX_LIMIT], z1q
jmp eight_blocks_loop
done_hash:
%ifndef LINUX
vmovdqa xmm6,[rsp + _XMM_SAVE + 0*16]
vmovdqa xmm7,[rsp + _XMM_SAVE + 1*16]
vmovdqa xmm8,[rsp + _XMM_SAVE + 2*16]
vmovdqa xmm9,[rsp + _XMM_SAVE + 3*16]
vmovdqa xmm10,[rsp + _XMM_SAVE + 4*16]
vmovdqa xmm11,[rsp + _XMM_SAVE + 5*16]
vmovdqa xmm12,[rsp + _XMM_SAVE + 6*16]
%endif
mov rsp, [rsp + _RSP]
mov a,[4*0 + CTX]
mov b,[4*1 + CTX]
mov c,[4*2 + CTX]
mov d,[4*3 + CTX]
mov e,[4*4 + CTX]
mov f,[4*5 + CTX]
mov g,[4*6 + CTX]
mov h,[4*7 + CTX]
bswap a
bswap b
bswap c
bswap d
bswap e
bswap f
bswap g
bswap h
mov [4*0 + CTX],a
mov [4*1 + CTX],b
mov [4*2 + CTX],c
mov [4*3 + CTX],d
mov [4*4 + CTX],e
mov [4*5 + CTX],f
mov [4*6 + CTX],g
mov [4*7 + CTX],h
pop r15
pop r14
pop r13
pop r12
pop rbp
%ifndef LINUX
pop rdi
pop rsi
%endif
pop rbx
ret
section .data
align 64
K256_SIMD:
ddq 0x428a2f98428a2f98428a2f98428a2f98,0x428a2f98428a2f98428a2f98428a2f98
ddq 0x71374491713744917137449171374491,0x71374491713744917137449171374491
ddq 0xb5c0fbcfb5c0fbcfb5c0fbcfb5c0fbcf,0xb5c0fbcfb5c0fbcfb5c0fbcfb5c0fbcf
ddq 0xe9b5dba5e9b5dba5e9b5dba5e9b5dba5,0xe9b5dba5e9b5dba5e9b5dba5e9b5dba5
ddq 0x3956c25b3956c25b3956c25b3956c25b,0x3956c25b3956c25b3956c25b3956c25b
ddq 0x59f111f159f111f159f111f159f111f1,0x59f111f159f111f159f111f159f111f1
ddq 0x923f82a4923f82a4923f82a4923f82a4,0x923f82a4923f82a4923f82a4923f82a4
ddq 0xab1c5ed5ab1c5ed5ab1c5ed5ab1c5ed5,0xab1c5ed5ab1c5ed5ab1c5ed5ab1c5ed5
ddq 0xd807aa98d807aa98d807aa98d807aa98,0xd807aa98d807aa98d807aa98d807aa98
ddq 0x12835b0112835b0112835b0112835b01,0x12835b0112835b0112835b0112835b01
ddq 0x243185be243185be243185be243185be,0x243185be243185be243185be243185be
ddq 0x550c7dc3550c7dc3550c7dc3550c7dc3,0x550c7dc3550c7dc3550c7dc3550c7dc3
ddq 0x72be5d7472be5d7472be5d7472be5d74,0x72be5d7472be5d7472be5d7472be5d74
ddq 0x80deb1fe80deb1fe80deb1fe80deb1fe,0x80deb1fe80deb1fe80deb1fe80deb1fe
ddq 0x9bdc06a79bdc06a79bdc06a79bdc06a7,0x9bdc06a79bdc06a79bdc06a79bdc06a7
ddq 0xc19bf174c19bf174c19bf174c19bf174,0xc19bf174c19bf174c19bf174c19bf174
ddq 0xe49b69c1e49b69c1e49b69c1e49b69c1,0xe49b69c1e49b69c1e49b69c1e49b69c1
ddq 0xefbe4786efbe4786efbe4786efbe4786,0xefbe4786efbe4786efbe4786efbe4786
ddq 0x0fc19dc60fc19dc60fc19dc60fc19dc6,0x0fc19dc60fc19dc60fc19dc60fc19dc6
ddq 0x240ca1cc240ca1cc240ca1cc240ca1cc,0x240ca1cc240ca1cc240ca1cc240ca1cc
ddq 0x2de92c6f2de92c6f2de92c6f2de92c6f,0x2de92c6f2de92c6f2de92c6f2de92c6f
ddq 0x4a7484aa4a7484aa4a7484aa4a7484aa,0x4a7484aa4a7484aa4a7484aa4a7484aa
ddq 0x5cb0a9dc5cb0a9dc5cb0a9dc5cb0a9dc,0x5cb0a9dc5cb0a9dc5cb0a9dc5cb0a9dc
ddq 0x76f988da76f988da76f988da76f988da,0x76f988da76f988da76f988da76f988da
ddq 0x983e5152983e5152983e5152983e5152,0x983e5152983e5152983e5152983e5152
ddq 0xa831c66da831c66da831c66da831c66d,0xa831c66da831c66da831c66da831c66d
ddq 0xb00327c8b00327c8b00327c8b00327c8,0xb00327c8b00327c8b00327c8b00327c8
ddq 0xbf597fc7bf597fc7bf597fc7bf597fc7,0xbf597fc7bf597fc7bf597fc7bf597fc7
ddq 0xc6e00bf3c6e00bf3c6e00bf3c6e00bf3,0xc6e00bf3c6e00bf3c6e00bf3c6e00bf3
ddq 0xd5a79147d5a79147d5a79147d5a79147,0xd5a79147d5a79147d5a79147d5a79147
ddq 0x06ca635106ca635106ca635106ca6351,0x06ca635106ca635106ca635106ca6351
ddq 0x14292967142929671429296714292967,0x14292967142929671429296714292967
ddq 0x27b70a8527b70a8527b70a8527b70a85,0x27b70a8527b70a8527b70a8527b70a85
ddq 0x2e1b21382e1b21382e1b21382e1b2138,0x2e1b21382e1b21382e1b21382e1b2138
ddq 0x4d2c6dfc4d2c6dfc4d2c6dfc4d2c6dfc,0x4d2c6dfc4d2c6dfc4d2c6dfc4d2c6dfc
ddq 0x53380d1353380d1353380d1353380d13,0x53380d1353380d1353380d1353380d13
ddq 0x650a7354650a7354650a7354650a7354,0x650a7354650a7354650a7354650a7354
ddq 0x766a0abb766a0abb766a0abb766a0abb,0x766a0abb766a0abb766a0abb766a0abb
ddq 0x81c2c92e81c2c92e81c2c92e81c2c92e,0x81c2c92e81c2c92e81c2c92e81c2c92e
ddq 0x92722c8592722c8592722c8592722c85,0x92722c8592722c8592722c8592722c85
ddq 0xa2bfe8a1a2bfe8a1a2bfe8a1a2bfe8a1,0xa2bfe8a1a2bfe8a1a2bfe8a1a2bfe8a1
ddq 0xa81a664ba81a664ba81a664ba81a664b,0xa81a664ba81a664ba81a664ba81a664b
ddq 0xc24b8b70c24b8b70c24b8b70c24b8b70,0xc24b8b70c24b8b70c24b8b70c24b8b70
ddq 0xc76c51a3c76c51a3c76c51a3c76c51a3,0xc76c51a3c76c51a3c76c51a3c76c51a3
ddq 0xd192e819d192e819d192e819d192e819,0xd192e819d192e819d192e819d192e819
ddq 0xd6990624d6990624d6990624d6990624,0xd6990624d6990624d6990624d6990624
ddq 0xf40e3585f40e3585f40e3585f40e3585,0xf40e3585f40e3585f40e3585f40e3585
ddq 0x106aa070106aa070106aa070106aa070,0x106aa070106aa070106aa070106aa070
ddq 0x19a4c11619a4c11619a4c11619a4c116,0x19a4c11619a4c11619a4c11619a4c116
ddq 0x1e376c081e376c081e376c081e376c08,0x1e376c081e376c081e376c081e376c08
ddq 0x2748774c2748774c2748774c2748774c,0x2748774c2748774c2748774c2748774c
ddq 0x34b0bcb534b0bcb534b0bcb534b0bcb5,0x34b0bcb534b0bcb534b0bcb534b0bcb5
ddq 0x391c0cb3391c0cb3391c0cb3391c0cb3,0x391c0cb3391c0cb3391c0cb3391c0cb3
ddq 0x4ed8aa4a4ed8aa4a4ed8aa4a4ed8aa4a,0x4ed8aa4a4ed8aa4a4ed8aa4a4ed8aa4a
ddq 0x5b9cca4f5b9cca4f5b9cca4f5b9cca4f,0x5b9cca4f5b9cca4f5b9cca4f5b9cca4f
ddq 0x682e6ff3682e6ff3682e6ff3682e6ff3,0x682e6ff3682e6ff3682e6ff3682e6ff3
ddq 0x748f82ee748f82ee748f82ee748f82ee,0x748f82ee748f82ee748f82ee748f82ee
ddq 0x78a5636f78a5636f78a5636f78a5636f,0x78a5636f78a5636f78a5636f78a5636f
ddq 0x84c8781484c8781484c8781484c87814,0x84c8781484c8781484c8781484c87814
ddq 0x8cc702088cc702088cc702088cc70208,0x8cc702088cc702088cc702088cc70208
ddq 0x90befffa90befffa90befffa90befffa,0x90befffa90befffa90befffa90befffa
ddq 0xa4506ceba4506ceba4506ceba4506ceb,0xa4506ceba4506ceba4506ceba4506ceb
ddq 0xbef9a3f7bef9a3f7bef9a3f7bef9a3f7,0xbef9a3f7bef9a3f7bef9a3f7bef9a3f7
ddq 0xc67178f2c67178f2c67178f2c67178f2,0xc67178f2c67178f2c67178f2c67178f2
PSHUFFLE_BYTE_FLIP_MASK: ddq 0x0c0d0e0f08090a0b0405060700010203
ddq 0x0c0d0e0f08090a0b0405060700010203
|
#include "../examples/utils.hpp"
#include <algorithm>
#include <catch.hpp>
#include <cmath>
#include <delaunator.hpp>
namespace {
constexpr double EPSILON = std::numeric_limits<double>::epsilon();
inline void validate(const std::vector<double>& coords, const double e) {
delaunator::Delaunator d(coords);
// validate halfedges
for (std::size_t i = 0; i < d.halfedges.size(); i++) {
const auto i2 = d.halfedges[i];
REQUIRE(!static_cast<bool>(
(i2 != delaunator::INVALID_INDEX) && (d.halfedges[i2] != i)));
}
//validate triangulation
double hull_area = d.get_hull_area();
std::vector<double> triangles_areas;
for (size_t i = 0; i < d.triangles.size(); i += 3) {
const double ax = coords[2 * d.triangles[i]];
const double ay = coords[2 * d.triangles[i] + 1];
const double bx = coords[2 * d.triangles[i + 1]];
const double by = coords[2 * d.triangles[i + 1] + 1];
const double cx = coords[2 * d.triangles[i + 2]];
const double cy = coords[2 * d.triangles[i + 2] + 1];
triangles_areas.push_back(std::fabs((by - ay) * (cx - bx) - (bx - ax) * (cy - by)));
}
double triangles_area = delaunator::sum(triangles_areas);
// printf("comparing %f == %f \n", triangles_area, hull_area);
REQUIRE(triangles_area == Approx(hull_area).epsilon(e));
}
inline void validate(const std::vector<double>& coords) {
validate(coords, EPSILON);
}
struct multiply {
double factor;
double operator()(double el) {
return el * factor;
}
};
} // namespace
TEST_CASE("triangles match JS version ouput", "[Delaunator]") {
std::string points_str = utils::read_file("./test/test-files/playgrounds-1356-epsg-3857.geojson");
std::string triangles_str = utils::read_file("./test/test-files/playgrounds-1356-triangles.json");
std::vector<double> coords = utils::get_geo_json_points(points_str);
std::vector<size_t> triangles = utils::get_array_points<size_t>(triangles_str);
delaunator::Delaunator delaunator(coords);
SECTION("length of triangles is the same") {
REQUIRE(delaunator.triangles.size() == triangles.size());
}
SECTION("values are the same") {
for (std::size_t i = 0; i < triangles.size(); i++) {
REQUIRE(delaunator.triangles[i] == triangles[i]);
}
}
}
TEST_CASE("produces correct triangulation", "[Delaunator]") {
std::vector<double> coords = { 168, 180, 168, 178, 168, 179, 168, 181, 168, 183, 167, 183, 167, 184, 165, 184, 162, 186, 164, 188, 161, 188, 160, 191, 158, 193, 156, 193, 152, 195, 152, 198, 150, 198, 147, 198, 148, 205, 150, 210, 148, 210, 148, 208, 145, 206, 142, 206, 140, 206, 138, 206, 135, 206, 135, 209, 131, 209, 131, 211, 127, 211, 124, 210, 120, 207, 120, 204, 120, 202, 124, 201, 123, 201, 125, 198, 125, 194, 127, 194, 127, 191, 130, 191, 132, 189, 134, 189, 134, 186, 136, 184, 134, 182, 134, 179, 134, 176, 136, 174, 139, 174, 141, 177, 142, 176, 144, 176, 147, 178, 148, 176, 151, 178, 154, 178, 153, 175, 152, 174, 152, 170, 152, 168, 150, 166, 148, 166, 147, 165, 145, 162, 146, 160, 146, 157, 146, 155, 144, 155, 142, 152, 140, 150, 138, 150, 138, 148, 140, 145, 140, 142, 140, 138, 139, 138, 137, 138, 135, 138, 133, 135, 132, 132, 129, 132, 128, 132, 124, 132, 124, 130, 123, 130, 118, 126, 116, 124, 112, 122, 109, 122, 105, 122, 102, 124, 100, 124, 97, 124, 95, 126, 92, 127, 89, 127, 88, 130, 85, 132, 80, 134, 72, 134, 69, 134, 65, 138, 64, 138, 58, 137, 56, 133, 52, 133, 51, 133, 48, 133, 44, 133, 41, 131, 38, 130, 35, 130, 32, 127, 30, 127, 27, 127, 24, 127, 24, 126, 23, 124, 20, 122, 17, 122, 16, 118, 15, 116, 15, 110, 18, 108, 20, 102, 24, 97, 28, 102, 28, 98, 26, 97, 28, 94, 27, 85, 29, 79, 32, 76, 39, 70, 44, 66, 48, 65, 53, 61, 53, 58, 51, 54, 54, 54, 52, 48, 51, 43, 48, 42, 49, 38, 48, 34, 51, 30, 53, 33, 58, 30, 61, 30, 60, 27, 64, 26, 68, 24, 74, 24, 80, 24, 85, 26, 92, 26, 96, 29, 103, 32, 109, 33, 112, 37, 116, 37, 120, 37, 124, 35, 126, 35, 128, 38, 132, 38, 134, 41, 138, 38, 140, 36, 142, 40, 144, 43, 145, 41, 149, 41, 155, 41, 159, 41, 161, 46, 165, 46, 164, 42, 164, 39, 164, 34, 167, 30, 173, 24, 178, 24, 184, 24, 189, 26, 195, 21, 195, 20, 199, 20, 203, 20, 207, 17, 211, 17, 216, 17, 218, 16, 222, 22, 225, 27, 228, 31, 226, 34, 224, 34, 226, 39, 228, 43, 230, 46, 236, 46, 242, 46, 243, 50, 245, 50, 247, 54, 247, 56, 248, 60, 248, 65, 253, 66, 255, 64, 260, 64, 264, 67, 268, 71, 272, 66, 275, 66, 281, 61, 285, 66, 286, 70, 292, 74, 294, 74, 296, 74, 296, 71, 301, 74, 307, 74, 311, 78, 315, 74, 315, 77, 319, 77, 322, 82, 328, 82, 331, 81, 331, 84, 333, 86, 333, 90, 330, 95, 326, 98, 328, 99, 332, 98, 333, 101, 331, 104, 329, 104, 327, 106, 329, 111, 332, 116, 333, 119, 333, 122, 332, 126, 332, 130, 327, 130, 321, 130, 317, 130, 315, 134, 312, 134, 308, 138, 306, 138, 306, 144, 306, 149, 306, 152, 301, 152, 297, 154, 295, 154, 292, 154, 292, 158, 288, 158, 283, 162, 281, 164, 279, 163, 276, 163, 273, 166, 272, 169, 268, 168, 265, 170, 260, 172, 256, 176, 252, 176, 248, 181, 246, 182, 246, 189, 246, 194, 248, 197, 250, 198, 252, 200, 252, 203, 254, 205, 260, 205, 264, 202, 267, 202, 269, 202, 272, 199, 280, 199, 278, 202, 278, 207, 278, 211, 276, 211, 272, 213, 268, 213, 265, 213, 264, 211, 262, 210, 260, 210, 257, 212, 257, 214, 255, 217, 253, 217, 253, 221, 249, 220, 247, 220, 243, 222, 240, 223, 239, 226, 234, 231, 229, 231, 224, 231, 219, 227, 220, 227, 222, 224, 222, 222, 222, 219, 224, 217, 222, 214, 220, 212, 217, 210, 215, 210, 211, 209, 208, 206, 202, 209, 202, 205, 206, 202, 211, 198, 216, 195, 220, 192, 224, 192, 221, 186, 218, 186, 214, 185, 208, 185, 204, 186, 200, 186, 193, 183, 190, 182, 188, 182, 190, 178, 186, 178, 184, 174, 182, 171, 178, 171, 173, 174, 169, 174, 169, 175, 169, 179, 167, 182, 164, 186, 160, 192, 155, 195, 152, 198, 150, 198, 148, 198, 148, 202, 151, 208, 148, 210, 146, 208, 144, 205, 140, 205, 137, 208, 132, 208, 132, 210, 127, 210, 124, 210, 120, 206, 120, 202, 123, 202, 124, 201, 124, 198, 128, 195, 131, 191, 133, 187, 135, 183, 130, 203, 129, 208, 123, 203, 129, 203, 129, 198, 133, 198, 136, 200, 142, 200, 143, 199, 143, 197, 137, 196, 136, 194, 133, 194, 136, 186, 136, 182, 141, 186, 144, 186, 150, 186, 150, 190, 155, 190, 159, 188, 156, 182, 151, 182, 144, 182, 164, 176, 161, 177, 157, 177, 166, 176, 168, 165, 175, 167, 180, 167, 188, 159, 195, 164, 195, 162, 187, 162, 178, 163, 173, 166, 168, 170, 156, 170, 157, 165, 164, 165, 164, 161, 170, 159, 167, 158, 159, 154, 149, 151, 145, 145, 145, 138, 152, 138, 152, 146, 159, 146, 165, 153, 176, 153, 180, 153, 187, 153, 194, 153, 202, 153, 202, 158, 197, 158, 193, 158, 193, 142, 180, 142, 171, 142, 163, 135, 176, 135, 186, 139, 201, 139, 206, 139, 205, 147, 205, 160, 198, 160, 206, 174, 205, 178, 196, 178, 196, 182, 202, 182, 206, 181, 209, 181, 215, 181, 222, 181, 230, 177, 238, 175, 241, 175, 237, 175, 237, 168, 237, 161, 232, 156, 231, 162, 225, 166, 217, 169, 210, 173, 224, 173, 227, 173, 235, 175, 237, 178, 228, 192, 222, 199, 216, 199, 211, 204, 205, 206, 219, 207, 222, 211, 229, 214, 236, 214, 244, 211, 247, 211, 268, 206, 277, 201, 279, 201, 281, 202, 278, 202, 242, 178, 236, 170, 236, 162, 255, 162, 251, 156, 240, 156, 253, 152, 261, 152, 277, 157, 268, 151, 255, 143, 260, 142, 267, 145, 271, 149, 273, 154, 258, 146, 257, 131, 256, 134, 248, 137, 260, 137, 260, 134, 271, 137, 276, 138, 276, 144, 289, 144, 285, 150, 294, 150, 298, 149, 301, 145, 292, 145, 282, 134, 276, 134, 283, 127, 282, 116, 277, 113, 283, 113, 288, 106, 296, 106, 297, 113, 297, 118, 298, 118, 310, 122, 310, 128, 300, 130, 300, 140, 292, 129, 292, 114, 283, 122, 289, 122, 299, 122, 299, 134, 294, 134, 288, 124, 314, 121, 311, 113, 308, 110, 304, 96, 299, 90, 299, 82, 305, 87, 309, 94, 311, 101, 312, 102, 314, 107, 320, 112, 320, 115, 326, 116, 323, 109, 321, 102, 321, 94, 321, 90, 328, 90, 328, 88, 316, 88, 316, 84, 307, 84, 290, 77, 289, 88, 289, 97, 278, 97, 268, 106, 268, 110, 261, 105, 255, 103, 244, 103, 252, 100, 252, 91, 252, 82, 242, 78, 252, 78, 259, 78, 264, 87, 267, 92, 272, 91, 272, 83, 264, 83, 260, 79, 276, 79, 283, 84, 283, 94, 289, 94, 284, 86, 272, 77, 253, 110, 248, 110, 239, 110, 234, 114, 222, 125, 219, 127, 219, 131, 219, 138, 219, 141, 224, 139, 224, 135, 225, 130, 232, 136, 240, 138, 237, 131, 237, 118, 248, 120, 256, 122, 262, 127, 255, 118, 245, 110, 207, 129, 199, 134, 195, 134, 188, 130, 180, 130, 165, 129, 156, 129, 165, 128, 173, 125, 185, 126, 193, 126, 201, 124, 204, 123, 208, 116, 214, 114, 207, 114, 196, 114, 183, 121, 183, 111, 189, 117, 196, 112, 172, 126, 164, 126, 159, 114, 174, 106, 186, 106, 192, 105, 184, 105, 184, 96, 173, 96, 163, 111, 159, 110, 152, 110, 168, 110, 171, 106, 183, 98, 193, 101, 219, 96, 225, 97, 225, 104, 232, 92, 240, 92, 237, 86, 229, 86, 216, 88, 214, 79, 203, 79, 203, 75, 212, 75, 221, 75, 229, 80, 230, 89, 217, 88, 217, 77, 228, 77, 228, 69, 235, 71, 240, 71, 244, 66, 236, 54, 236, 62, 232, 68, 229, 61, 216, 61, 212, 58, 212, 47, 212, 39, 214, 28, 215, 48, 225, 55, 236, 55, 202, 65, 202, 54, 202, 44, 202, 24, 198, 32, 199, 38, 192, 38, 185, 38, 174, 42, 174, 48, 178, 51, 184, 51, 194, 55, 191, 68, 182, 68, 174, 69, 167, 67, 153, 59, 153, 49, 147, 49, 152, 58, 152, 74, 154, 83, 161, 83, 165, 88, 153, 97, 153, 89, 152, 82, 168, 88, 168, 101, 156, 102, 156, 119, 173, 110, 184, 110, 177, 106, 160, 106, 145, 125, 137, 122, 131, 120, 124, 120, 122, 118, 113, 118, 114, 111, 129, 111, 140, 110, 143, 106, 137, 102, 127, 102, 119, 98, 126, 93, 139, 93, 139, 99, 141, 95, 128, 89, 118, 74, 128, 76, 135, 76, 141, 83, 141, 71, 137, 61, 137, 50, 129, 50, 118, 50, 109, 52, 112, 61, 123, 60, 134, 60, 129, 76, 121, 67, 124, 76, 123, 76, 111, 74, 128, 73, 109, 83, 109, 94, 105, 103, 102, 118, 92, 113, 98, 105, 99, 93, 94, 93, 94, 81, 99, 81, 100, 73, 100, 89, 100, 60, 100, 55, 105, 37, 101, 34, 93, 37, 90, 37, 90, 49, 99, 49, 88, 68, 80, 68, 78, 64, 88, 62, 86, 77, 76, 89, 71, 91, 71, 106, 78, 106, 82, 118, 84, 110, 71, 104, 76, 103, 76, 91, 78, 83, 85, 89, 83, 103, 83, 119, 76, 130, 62, 130, 68, 127, 74, 126, 83, 123, 62, 123, 56, 123, 59, 129, 59, 120, 49, 110, 46, 106, 56, 100, 62, 94, 62, 109, 72, 112, 67, 112, 57, 112, 61, 122, 60, 102, 52, 125, 44, 121, 36, 114, 32, 110, 20, 110, 22, 118, 35, 118, 44, 124, 32, 119, 22, 111, 44, 96, 36, 106, 36, 94, 32, 94, 35, 83, 44, 91, 52, 91, 52, 80, 59, 80, 62, 76, 62, 70, 47, 78, 55, 75, 64, 71, 64, 60, 58, 53, 58, 43, 65, 43, 65, 60, 76, 52, 73, 38, 76, 36, 93, 48, 89, 39, 99, 40, 98, 50, 94, 63, 117, 63, 131, 67, 131, 74, 142, 78, 140, 61, 124, 58, 124, 48, 136, 55, 236, 200, 228, 200, 226, 192, 232, 198, 238, 210, 248, 210, 236, 220, 230, 223, 230, 213, 175, 32, 172, 32, 171, 38, 184, 30 };
validate(coords);
}
TEST_CASE("mapbox/delaunator/issues/11", "[Delaunator]") {
std::vector<double> coords = { 516, 661, 369, 793, 426, 539, 273, 525, 204, 694, 747, 750, 454, 390 };
validate(coords);
}
TEST_CASE("mapbox/delaunator/issues/24", "[Delaunator]") {
std::vector<double> coords = { 382, 302, 382, 328, 382, 205, 623, 175, 382, 188, 382, 284, 623, 87, 623, 341, 141, 227 };
validate(coords);
}
TEST_CASE("mapbox/delaunator/issues/13", "[Delaunator]") {
std::vector<double> coords = { 4, 1, 3.7974166882130675, 2.0837249985614585, 3.2170267516619773, 3.0210869309396715, 2.337215067329615, 3.685489874065187, 1.276805078389906, 3.9872025288851036, 0.17901102978375127, 3.885476929518457, -0.8079039091377689, 3.3940516818407187, -1.550651407188842, 2.5792964886320684, -1.9489192990517052, 1.5512485534497125, -1.9489192990517057, 0.44875144655029087, -1.5506514071888438, -0.5792964886320653, -0.8079039091377715, -1.394051681840717, 0.17901102978374794, -1.8854769295184561, 1.276805078389902, -1.987202528885104, 2.337215067329611, -1.6854898740651891, 3.217026751661974, -1.021086930939675, 3.7974166882130653, -0.08372499856146409 };
validate(coords);
}
TEST_CASE("robustness", "[Delaunator]") {
std::vector<double> coords = { 66.103648384371410, 68.588612471664760, 146.680713462100413, 121.680713462100428, 128.868896560467447, 117.261797559041411, 66.103648384371439, 68.588612471664774, 169.552139667571992, 146.133776538276890, 126.629392246050883, 181.111404660392082, 74.434448280233709, 78.630898779520691, 121.111404660392054, 153.370607753949116, 98.888595339607888, 186.629392246050855, 52.660668968140221, 63.178539267712423, 85.321337936280443, 86.357078535424832, 129.615705608064615, 173.901806440322616, 91.522409349774278, 162.346331352698143, 137.240951282800551, 112.240951282800537, 93.370607753949116, 158.888595339607917, 175, 150, 124.142135623730908, 184.142135623730979, 96.208227592327205, 94.083258291328988, 98.888595339607988, 153.370607753949059, 117.982006904420700, 109.535617803137270, 116.194470264303831, 108.267043413376910, 54.324378061245710, 62.306334965997713, 30.886889656046740, 47.726179755904141, 107.095117248373952, 101.809438047233129, 38.892261948632665, 52.594841299088443, 146.680713462100413, 121.680713462100399, 95.857864376269077, 155.857864376269020, 54.324378061245703, 62.306334965997706, 137.240951282800551, 112.240951282800551, 161.529565528607690, 140.440336826753821, 90.384294391935398, 166.098193559677383, 113.220729676874285, 93.717722494332946, 77.882918707497154, 74.870889977331813, 50, 60, 85.321337936280457, 86.357078535424847, 41.773779312093481, 55.452359511808289, 89.662189030622869, 81.153167482998867, 101.441459353748570, 87.435444988665906, 124.142135623730965, 155.857864376269048, 172.416455184654381, 148.166516582657948, 63.547558624186912, 70.904719023616522, 150.642675872560943, 132.714157070849694, 109.999999999999928, 190, 128.477590650225721, 177.653668647301827, 90, 169.999999999999943, 128.477590650225749, 162.346331352698200, 156.120475641400275, 131.120475641400275, 90.384294391935384, 173.901806440322502, 95.857864376268992, 184.142135623730894, 77.882918707497140, 74.870889977331799, 139.755786216514195, 124.987977314945553, 130, 170, 102.346331352698129, 188.477590650225693, 41.773779312093481, 55.452359511808282, 91.522409349774235, 177.653668647301714, 27.784523897265298, 45.189682598176865, 126.629392246050912, 158.888595339607974, 106.098193559677355, 189.615705608064587, 52.660668968140200, 63.178539267712395, 74.434448280233681, 78.630898779520677, 106.098193559677469, 150.384294391935384, 117.653668647301728, 188.477590650225749, 125, 100, 38.892261948632565, 52.594841299088379, 52.660668968140228, 63.178539267712416, 129.615705608064615, 166.098193559677440, 20, 40, 117.653668647301813, 151.522409349774278, 161.529565528607662, 140.440336826753821, 63.547558624186969, 70.904719023616564, 127.801189103500675, 102.801189103500675, 89.662189030622840, 81.153167482998853, 102.346331352698243, 151.522409349774250, 93.370607753949059, 181.111404660391968, 113.901806440322502, 189.615705608064615, 121.111404660391997, 186.629392246050940, 113.901806440322587, 150.384294391935384, 110.000000000000028, 150, 165.560237820700137, 140.560237820700137 };
std::vector<double> coords_result;
coords_result.resize(coords.size());
validate(coords);
std::transform(coords.begin(), coords.end(), coords_result.begin(), multiply{ 1e-2 });
validate(coords_result);
std::transform(coords.begin(), coords.end(), coords_result.begin(), multiply{ 1e-9 });
validate(coords_result);
std::transform(coords.begin(), coords.end(), coords_result.begin(), multiply{ 1e2 });
validate(coords_result, EPSILON * 2.0); //TODO: missing triangle?
std::transform(coords.begin(), coords.end(), coords_result.begin(), multiply{ 1e9 });
validate(coords_result);
std::vector<double> coords1 = { 66.103648384371410, 68.588612471664760, 146.680713462100413, 121.680713462100428, 128.868896560467447, 117.261797559041411, 66.103648384371439, 68.588612471664774, 169.552139667571992, 146.133776538276890, 126.629392246050883, 181.111404660392082, 74.434448280233709, 78.630898779520691, 121.111404660392054, 153.370607753949116, 98.888595339607888, 186.629392246050855, 52.660668968140221, 63.178539267712423, 85.321337936280443, 86.357078535424832, 129.615705608064615, 173.901806440322616, 91.522409349774278, 162.346331352698143, 137.240951282800551, 112.240951282800537, 93.370607753949116, 158.888595339607917, 175, 150, 124.142135623730908, 184.142135623730979, 96.208227592327205, 94.083258291328988, 98.888595339607988, 153.370607753949059, 117.982006904420700, 109.535617803137270, 116.194470264303831, 108.267043413376910, 54.324378061245710, 62.306334965997713, 30.886889656046740, 47.726179755904141, 107.095117248373952, 101.809438047233129, 38.892261948632665, 52.594841299088443, 146.680713462100413, 121.680713462100399, 95.857864376269077, 155.857864376269020, 54.324378061245703, 62.306334965997706, 137.240951282800551, 112.240951282800551, 161.529565528607690, 140.440336826753821, 90.384294391935398, 166.098193559677383, 113.220729676874285, 93.717722494332946, 77.882918707497154, 74.870889977331813, 50, 60, 85.321337936280457, 86.357078535424847, 41.773779312093481, 55.452359511808289, 89.662189030622869, 81.153167482998867, 101.441459353748570, 87.435444988665906, 124.142135623730965, 155.857864376269048, 172.416455184654381, 148.166516582657948, 63.547558624186912, 70.904719023616522, 150.642675872560943, 132.714157070849694, 109.999999999999928, 190, 128.477590650225721, 177.653668647301827, 90, 169.999999999999943, 128.477590650225749, 162.346331352698200, 156.120475641400275, 131.120475641400275, 90.384294391935384, 173.901806440322502, 95.857864376268992, 184.142135623730894, 77.882918707497140, 74.870889977331799, 139.755786216514195, 124.987977314945553, 130, 170, 102.346331352698129, 188.477590650225693, 41.773779312093481, 55.452359511808282, 91.522409349774235, 177.653668647301714, 27.784523897265298, 45.189682598176865, 126.629392246050912, 158.888595339607974, 106.098193559677355, 189.615705608064587, 52.660668968140200, 63.178539267712395, 74.434448280233681, 78.630898779520677, 106.098193559677469, 150.384294391935384, 117.653668647301728, 188.477590650225749, 125, 100, 38.892261948632565, 52.594841299088379, 52.660668968140228, 63.178539267712416, 129.615705608064615, 166.098193559677440, 20, 40, 117.653668647301813, 151.522409349774278, 161.529565528607662, 140.440336826753821, 63.547558624186969, 70.904719023616564, 127.801189103500675, 102.801189103500675, 89.662189030622840, 81.153167482998853, 102.346331352698243, 151.522409349774250, 93.370607753949059, 181.111404660391968, 113.901806440322502, 189.615705608064615, 121.111404660391997, 186.629392246050940, 113.901806440322587, 150.384294391935384, 110.000000000000028, 150, 165.560237820700137, 140.560237820700137 };
validate(coords1);
std::vector<double> coords2 = { 0.226270008640849, -0.5484478681473859, 0.22627000864084906, -0.5484478681473857, 0.766192698520777, -0.06114560279536302, 0.7661926985207771, -0.06114560279536302, 0.40151121510492016, 0.08616979557470032, 0.40151121510492027, 0.08616979557470034, -0.41675996433129736, -0.5902787491305856, -0.4167599643312972, -0.5902787491305853, -0.2479064469635639, -0.7472011647497873, -0.24790644696356384, -0.7472011647497872, 0.6078988481689899, -0.8087190266174613, 0.6078988481689901, -0.808719026617461, 0.6844238681986647, -0.22229148851718702, 0.6844238681986647, -0.222291488517187, 0.6486832941181451, 0.3706194950394349, 0.6486832941181452, 0.3706194950394349, -0.5361048842131249, -0.16765691382574804, -0.5361048842131245, -0.167656913825748, 0.4588358986737203, -0.9000280551977525, 0.4588358986737205, -0.9000280551977525, 0.3960651926938643, 0.19117525930527385, 0.39606519269386437, 0.1911752593052739, 0.30699987842448867, -0.4067155996580057, 0.3069998784244887, -0.4067155996580056, 0.47811583559881354, 0.4551485080955586, 0.47811583559881354, 0.4551485080955586, 0.5569494202770435, 0.3174275448747843, 0.5569494202770439, 0.3174275448747845, -0.4277027605175392, 0.09695587866512022, -0.4277027605175391, 0.09695587866512025, -0.5748114807265807, -0.03838218657575568, -0.5748114807265806, -0.03838218657575567, -1.0317070883952917, -0.5245256032470283, -1.031707088395291, -0.5245256032470283, 0.14712374452633492, 0.33141471681448986, 0.147123744526335, 0.33141471681448986, -0.2834737219004291, -0.9271587984120542, -0.2834737219004289, -0.9271587984120538, -0.6098149486946731, 0.5553773725836295, -0.6098149486946729, 0.5553773725836295, 1.1206314478250745, 0.3921423623286639, 1.1206314478250745, 0.39214236232866406, 0.4477538973665876, -0.04256704865570235, 0.4477538973665877, -0.04256704865570235, -0.6156635308889042, -0.10817302193016937, -0.6156635308889041, -0.10817302193016932, 0.17897362794557034, -0.04224227852769616, 0.17897362794557034, -0.04224227852769614, -0.9646885789850332, -1.4563419829050452, -0.9646885789850331, -1.456341982905045, 0.2911613415160255, 0.015655417967490592, 0.29116134151602563, 0.015655417967490596, -0.3698918540831971, 0.6983267205999204, -0.3698918540831969, 0.6983267205999205, 1.4056553730213062, -0.41615789580202767, 1.4056553730213066, -0.41615789580202767, 0.34141990921721344, -0.5679551502988661, 0.3414199092172136, -0.5679551502988661, 0.2957318137669341, 0.8416499601535058, 0.29573181376693425, 0.841649960153506, 0.035141462612931273, -0.45835970615650135, 0.03514146261293129, -0.45835970615650123, -1.3263110033694971, 0.8223290351908346, -1.326311003369497, 0.8223290351908346, -0.18787969354847422, 1.4601214758378256, -0.18787969354847417, 1.4601214758378258, -0.5421684590742957, -0.5196118080038157, -0.5421684590742956, -0.5196118080038157, -0.15415956428809274, 0.2553265483092856, -0.15415956428809266, 0.25532654830928564, 0.24744639466303925, 0.36561549310806263, 0.24744639466303933, 0.36561549310806274, -0.007949225522230624, -0.4463313570187974, -0.00794922552223062, -0.4463313570187972, 0.4314282749865176, 0.6907165244683744, 0.4314282749865177, 0.6907165244683744, 0.22721916356346672, -1.145924985720078, 0.22721916356346675, -1.1459249857200775, 0.11627266697915434, 0.5679584977485386, 0.11627266697915438, 0.5679584977485389, -0.004760241854834868, 1.341758406463988, -0.004760241854834866, 1.3417584064639887, 0.34070213758085, -0.4524446934513693, 0.3407021375808501, -0.45244469345136923, 0.8842875090593054, -0.4369329059094983, 0.8842875090593055, -0.43693290590949824, 0.1514286184534766, -0.17725085421066233, 0.15142861845347666, -0.17725085421066225, -0.4255258812089902, -0.48986352859695054, -0.42552588120899015, -0.4898635285969505, 0.9377261482762783, -0.1443481348548356, 0.9377261482762784, -0.14434813485483552, 0.04260345503852292, 0.951377045867543, 0.04260345503852292, 0.951377045867543, 0.305243584013604, -0.3875472629266138, 0.305243584013604, -0.3875472629266138, 0.03603755940893599, 0.34504467425927055, 0.036037559408936, 0.34504467425927055, 0.7432869522329792, -0.7836440067269177, 0.7432869522329795, -0.7836440067269175, -0.2963957383054346, -0.8541077824286829, -0.2963957383054344, -0.8541077824286829, -0.5957774790480242, -0.600709712349726, -0.5957774790480241, -0.6007097123497258, -0.16224562470708315, 0.34537414926581733, -0.16224562470708306, 0.34537414926581733, -0.7424662163367453, -0.41130625924230096, -0.742466216336745, -0.41130625924230085, -0.3624590396531042, -0.10563984421746442, -0.3624590396531041, -0.10563984421746442, -0.5392904110560361, -0.08518185259429017, -0.5392904110560358, -0.08518185259429016, -0.6778672159722301, 0.3431673449069855, -0.6778672159722301, 0.3431673449069856, 0.36715717958832705, -0.5910728761089766, 0.36715717958832716, -0.5910728761089764, -0.025023155416355747, 0.049551540818041445, -0.025023155416355747, 0.04955154081804146, -0.24819669042158904, 1.551076727423892, -0.24819669042158898, 1.5510767274238921, 0.567193157662795, 0.11906741314152564, 0.567193157662795, 0.11906741314152564, -0.040143445247768667, 0.26972252794743534, -0.04014344524776866, 0.26972252794743534, -0.2625294670890006, -0.9866393501381076, -0.2625294670890005, -0.9866393501381073, 0.44843907219373064, 0.8048081754922025, 0.44843907219373064, 0.8048081754922027, 0.0645600537587031, 1.0817638655728792, 0.06456005375870313, 1.0817638655728798, 0.7675432088110417, -0.8812717114610312, 0.7675432088110417, -0.8812717114610309, -0.08286494268897, -0.4289421536808215, -0.08286494268896998, -0.42894215368082134, -0.41612370586918423, 0.4886715855834002, -0.41612370586918423, 0.48867158558340035, 0.19771717248920714, -0.1094932114101852, 0.19771717248920723, -0.10949321141018517, 0.3325743770435765, 0.3050059606614455, 0.3325743770435766, 0.3050059606614456, -0.6076675750885592, -0.2488880571567846, -0.6076675750885588, -0.24888805715678455, -0.13216710101702264, -0.5066473875502346, -0.13216710101702256, -0.5066473875502345, 0.8513876721292416, -0.5489241609365357, 0.8513876721292416, -0.5489241609365356, -0.382289175026138, -0.47285448091622573, -0.38228917502613796, -0.4728544809162256, -0.22454842691828375, 0.6151379112650053, -0.22454842691828367, 0.6151379112650056, -0.8646014175536286, -0.42386569643498184, -0.8646014175536284, -0.4238656964349818, 0.3117316226386966, 0.2627613357418179, 0.3117316226386967, 0.262761335741818, -0.15249103914387663, 0.4395379613315442, -0.15249103914387657, 0.4395379613315443, -0.8535303948590758, -0.5171136892316436, -0.8535303948590756, -0.5171136892316435, 0.5548908499705427, 0.7505471621260598, 0.5548908499705427, 0.7505471621260601, -0.06051133138765111, 0.10241755750407933, -0.0605113313876511, 0.10241755750407933, 0.5337288423213871, -0.4674709006951539, 0.5337288423213873, -0.4674709006951539, 0.05432726705458686, 0.7404240043361822, 0.054327267054586875, 0.7404240043361824, 0.18755513858332273, -0.33846461008241124, 0.1875551385833228, -0.33846461008241124, -0.8591170242442958, 0.10096092456106642, -0.8591170242442956, 0.10096092456106642, -0.6532878500824677, 0.06191743854152687, -0.6532878500824675, 0.06191743854152687, -0.8539614587215372, -0.7324824009962402, -0.8539614587215372, -0.7324824009962402, -0.5863802667964559, -1.056546154929931, -0.5863802667964556, -1.0565461549299304, -0.1790469166305501, 0.2959320232236789, -0.17904691663055006, 0.2959320232236789, -0.1360834565364501, -0.11972427421383847, -0.13608345653645007, -0.11972427421383845, 1.000279652308404, 0.5677840712010568, 1.0002796523084043, 0.5677840712010568, -0.2539417014734854, -0.24824262411661902, -0.2539417014734853, -0.24824262411661896, -0.5513314210236925, 0.164455936053998, -0.5513314210236921, 0.16445593605399808, -0.35669084505120763, -0.5579365995173293, -0.3566908450512076, -0.557936599517329, -0.00479028693868494, 0.5747959597699825, -0.004790286938684939, 0.5747959597699829, 0.9274618857336762, 0.3137388167061812, 0.9274618857336765, 0.3137388167061813, -0.1582654462645559, 0.08532244403569378, -0.1582654462645559, 0.08532244403569382, -0.7338606250043278, 0.03884536523072413, -0.7338606250043278, 0.038845365230724134, 0.441630546674704, -0.4757978998267975, 0.4416305466747042, -0.4757978998267975, -0.340639188849867, -0.016461235375619054, -0.340639188849867, -0.01646123537561905, 0.6944973204450795, -0.05127049077067958, 0.6944973204450798, -0.051270490770679564, 0.05692195764635159, -0.4860234898913355, 0.05692195764635161, -0.4860234898913355, -0.34909544551668503, 0.07925987763994416, -0.3490954455166849, 0.07925987763994416, 0.020842670418798892, -0.18962128485770935, 0.020842670418798902, -0.1896212848577093, -0.24296262993119017, -0.7557062436624338, -0.24296262993119008, -0.7557062436624334, 0.07767785036524773, -0.0756745138376198, 0.07767785036524774, -0.0756745138376198, -0.5383587124935423, 0.3149908402335876, -0.538358712493542, 0.3149908402335876, -0.3672547557130592, 0.8497352282145765, -0.3672547557130592, 0.8497352282145768, 1.0306858576839981, 0.6132170100848149, 1.0306858576839986, 0.6132170100848152, 0.026403641820751278, -0.11123958700346126, 0.02640364182075129, -0.11123958700346125, -0.39673068933170313, 0.7365210212380586, -0.3967306893317031, 0.7365210212380586, -0.273859110739041, 0.15083421880672626, -0.2738591107390409, 0.15083421880672626, -0.7502503591118193, -0.6273750425323015, -0.7502503591118191, -0.6273750425323014, 1.040458273889268, 0.3592162639445413, 1.0404582738892683, 0.3592162639445414, -0.30951481303178596, -0.7990197975684153, -0.30951481303178585, -0.7990197975684152, -0.3049861667890695, 1.6737307580052914, -0.30498616678906937, 1.673730758005292, 0.601935475297747, 1.1660575124169412, 0.601935475297747, 1.1660575124169419, 0.8838992370838099, 0.2656415636074353, 0.8838992370838102, 0.2656415636074353, -0.5085727248068516, -0.23584500534815295, -0.5085727248068515, -0.2358450053481529, 0.5396217328637709, -0.39810497658583466, 0.5396217328637712, -0.39810497658583466, 0.8665494841240842, 0.11624211166929022, 0.8665494841240843, 0.11624211166929023, -0.51942267345288, 0.5395224235439922, -0.5194226734528796, 0.5395224235439922, 0.19088288221197763, -0.4663336215970121, 0.19088288221197763, -0.4663336215970119, -0.23194847381262582, 0.21901474700861162, -0.23194847381262573, 0.21901474700861162, 0.8359436402369345, -0.2679779650730807, 0.8359436402369346, -0.2679779650730805, 0.4468309121482219, 0.724738511770195, 0.4468309121482219, 0.7247385117701953, 0.5963791684457523, 0.8746079737915003, 0.5963791684457525, 0.8746079737915007, -0.16268657840268694, -0.10458689278692812, -0.16268657840268685, -0.10458689278692809, 0.15167543844454376, 0.3810633395493045, 0.1516754384445438, 0.3810633395493046, 0.3175047149330903, -0.4680659139099735, 0.31750471493309046, -0.4680659139099735, 0.24518019737678892, 0.14105859064554405, 0.24518019737678892, 0.1410585906455441, 0.1337014618382204, 0.216053384319761, 0.1337014618382205, 0.21605338431976104, -0.5196743788563577, -0.24381508621133063, -0.5196743788563577, -0.24381508621133063, 0.16145768845022127, -0.18548235309792105, 0.16145768845022135, -0.18548235309792097, 0.5267956022472777, -0.07806817831728718, 0.5267956022472777, -0.07806817831728716, 0.2690528801662905, 0.007775444056135339, 0.2690528801662905, 0.00777544405613534, 0.7565821160819859, -0.3047749278545374, 0.7565821160819859, -0.30477492785453736, -0.7016467625353928, 0.04470959700747512, -0.7016467625353925, 0.04470959700747514, 0.2415239307661166, 0.2972238198129453, 0.24152393076611664, 0.2972238198129453, 0.2284592008150542, -0.6608245027366711, 0.2284592008150542, -0.6608245027366711, 0.2123088556780684, 0.01782161739519142, 0.21230885567806848, 0.017821617395191426, -0.14619514581307758, -0.8833238459080084, -0.14619514581307758, -0.8833238459080082, 0.1989466009909055, -0.6118402241082294, 0.1989466009909055, -0.6118402241082291, 0.49059993119084305, -0.16493514201871323, 0.4905999311908431, -0.1649351420187132, -0.4129648372506063, -0.05944366961592451, -0.4129648372506062, -0.059443669615924496, 0.586485692893329, 0.3271185970911774, 0.5864856928933292, 0.32711859709117747, -0.06023227911161408, -0.7107842875157466, -0.06023227911161407, -0.7107842875157466, 0.6310359079249456, 0.29992699270395096, 0.6310359079249456, 0.29992699270395107, -0.6703089300986523, 0.6107470941705689, -0.670308930098652, 0.6107470941705689, 0.5005957282133777, 0.01407262429060302, 0.500595728213378, 0.014072624290603021, -0.18934890988546538, -0.9372780070318394, -0.1893489098854653, -0.9372780070318394, -0.2863087126284564, -0.40444718862380247, -0.28630871262845636, -0.4044471886238023, 1.190084782443751, 0.5322874598725964, 1.1900847824437517, 0.5322874598725967, 0.1341442916393324, -0.8420626196661292, 0.13414429163933247, -0.8420626196661289, -0.7649861084427345, -0.7071073574041574, -0.7649861084427344, -0.7071073574041573, -0.362881463482392, 0.4530261596665785, -0.3628814634823919, 0.45302615966657866, 0.13437240869925704, 0.0763221848731111, 0.13437240869925712, 0.0763221848731111, 1.0481657649638807, -0.004257185833033583, 1.0481657649638814, -0.004257185833033581, -0.7474948815245823, -0.9786844358659653, -0.7474948815245823, -0.9786844358659653, 0.12735871993303205, -0.3185548367971229, 0.12735871993303208, -0.31855483679712276, 0.36855220211615, -0.5588123239347687, 0.36855220211615003, -0.5588123239347685, -0.18314335566244416, -0.5442250179734792, -0.18314335566244408, -0.544225017973479, 0.08693873231351551, -0.6447286294698766, 0.08693873231351551, -0.6447286294698766, -0.05481436374055537, 0.20956141264894845, -0.05481436374055537, 0.2095614126489485, -0.27114580055426557, 0.12928945128646963, -0.2711458005542655, 0.12928945128646968, -0.4451760474692624, 0.46862844610576626, -0.4451760474692623, 0.4686284461057663, 0.1341730804119372, -0.5079494612186458, 0.13417308041193723, -0.5079494612186456, 0.3257440025696646, 0.4153507171529827, 0.3257440025696647, 0.4153507171529827, -1.2231311278955395, 0.5704928559937266, -1.223131127895539, 0.5704928559937269, -0.07375248343426033, -0.5524759317685063, -0.0737524834342603, -0.5524759317685063, -0.6413383012441964, -0.3892879515624541, -0.6413383012441963, -0.38928795156245405, -0.000884182358095037, -0.003185720596142992, -0.0008841823580950368, -0.003185720596142991, 0.737566803637365, -0.7615040446353664, 0.7375668036373654, -0.761504044635366, 0.23446047289831606, 0.19035505393365781, 0.23446047289831606, 0.19035505393365784, -0.07211988377390469, -0.13169854040950443, -0.07211988377390469, -0.13169854040950443, 0.18143877838398617, 1.132013860293268, 0.18143877838398625, 1.1320138602932683, -0.22066292105815377, -0.19117568196580417, -0.22066292105815372, -0.19117568196580417, -0.4347453028054331, 0.5888401578252912, -0.43474530280543294, 0.5888401578252915, 0.24005504098930414, 0.8021441938204985, 0.24005504098930416, 0.8021441938204986, -0.34929799898447755, -0.261775797658851, -0.34929799898447744, -0.26177579765885084, 0.3490077668059596, -0.007752337813972554, 0.3490077668059597, -0.0077523378139725515, -0.6025788068137587, 0.46068756636034236, -0.6025788068137585, 0.4606875663603424, -0.7122333712891852, 0.26308462754739115, -0.7122333712891852, 0.26308462754739115, 0.15764425398809745, 0.18964163728856187, 0.15764425398809748, 0.18964163728856193, 0.1853787174021873, -0.6789040209134625, 0.18537871740218737, -0.6789040209134621, 0.634911453390334, 0.13339968677329644, 0.6349114533903343, 0.13339968677329647, -1.2578415170869763, 0.2517963788258869, -1.2578415170869757, 0.2517963788258869, 0.1400845593846478, 0.40593141307431857, 0.14008455938464787, 0.4059314130743186, -0.7095485725512902, 0.8225233205642902, -0.7095485725512899, 0.8225233205642903, -1.1960848307098382, 0.17404679607890605, -1.196084830709838, 0.17404679607890608, 0.21828979413603433, -0.3280264848946596, 0.2182897941360344, -0.3280264848946595, 0.2662387358530971, 0.3568929623829047, 0.26623873585309726, 0.3568929623829048, 0.24305026107578037, -0.23724020319018074, 0.24305026107578043, -0.23724020319018066, -0.3433832627650342, 0.3389417719770061, -0.34338326276503406, 0.3389417719770061, -0.0437269904343551, 0.5869495454659391, -0.04372699043435508, 0.5869495454659392, -0.12109570623011018, -0.8772834803160542, -0.12109570623011016, -0.8772834803160542, 0.09631218123471452, -0.12108887934946555, 0.09631218123471456, -0.12108887934946555, -0.41811390046020547, 0.8465092639539217, -0.4181139004602053, 0.8465092639539218, -0.34396631561394114, 0.8358904797678759, -0.343966315613941, 0.8358904797678759, 0.43085589801084057, -0.16054297058369527, 0.4308558980108406, -0.1605429705836952, -0.19787245165430847, 0.8949780141072381, -0.19787245165430842, 0.8949780141072381, -0.5907860100454578, 0.18974221311023962, -0.5907860100454575, 0.18974221311023964, -0.5306691342020886, -0.7275053842709899, -0.5306691342020886, -0.7275053842709899, -0.345074608245379, 1.207589321519286, -0.34507460824537883, 1.207589321519286, -0.32302823411726667, 0.08250252511437048, -0.32302823411726667, 0.0825025251143705, -0.1000939664088763, -1.056428113867832, -0.10009396640887627, -1.056428113867832, 0.0057223538613018765, -0.07997801149692216, 0.005722353861301878, -0.07997801149692216, -1.0232923766303312, 0.22905472765407248, -1.0232923766303312, 0.22905472765407253, -0.04071787429636753, 0.03839904161757046, -0.04071787429636751, 0.03839904161757047, -0.5114614823431506, -0.0673439850879256, -0.5114614823431503, -0.06734398508792559, -0.033395285925899576, -0.25197193535594753, -0.03339528592589957, -0.2519719353559475, -1.3238866550876203, -0.34335648499193994, -1.3238866550876196, -0.3433564849919398, 0.3098949809621799, -0.692558554406312, 0.30989498096218, -0.6925585544063119, -0.7778172969650805, -0.7251725696504421, -0.7778172969650804, -0.7251725696504421, 0.5832467520992983, -0.0005585979375463679, 0.5832467520992983, -0.0005585979375463677, 0.6402717430536337, -0.24460516745019825, 0.6402717430536337, -0.24460516745019825, 0.3744231501345624, 0.23752933224278633, 0.37442315013456257, 0.23752933224278638, -0.5526534599107001, 0.2959174882702319, -0.5526534599106999, 0.29591748827023195, 0.0870980709703463, 0.011155933053077993, 0.08709807097034632, 0.011155933053077997, 0.10294466025799387, 0.6246279155358483, 0.10294466025799387, 0.6246279155358484, 0.7907530514131953, 0.7968130944966136, 0.7907530514131955, 0.796813094496614, -0.06771348768905705, -0.19742894579933645, -0.06771348768905704, -0.19742894579933642, 1.7336246702438183, -0.08111369728186346, 1.7336246702438185, -0.08111369728186343, 0.39279504341227045, -0.2803428186493195, 0.39279504341227056, -0.2803428186493194, -0.3837990187335033, 0.5817465996045292, -0.38379901873350314, 0.5817465996045292, -0.15897299229161954, 0.2123178635236439, -0.15897299229161949, 0.21231786352364398, 1.2871753315186103, -0.2936546706485327, 1.2871753315186105, -0.2936546706485326, -0.28157817609809926, 0.015215204873323618, -0.28157817609809926, 0.015215204873323621, -0.8407785771058587, 0.11715953275528568, -0.8407785771058583, 0.11715953275528568, 0.057427665729494065, 0.17741033446395021, 0.057427665729494086, 0.17741033446395027, -0.3919333534914909, -0.8777063099779623, -0.3919333534914909, -0.8777063099779623, 1.046062759037447, 0.12566529633175702, 1.0460627590374476, 0.1256652963317571, 0.05208282489856039, 0.23074154552008772, 0.05208282489856039, 0.23074154552008772, 0.3090093991217477, -0.28949051651550656, 0.3090093991217478, -0.2894905165155065, -0.903992079888195, -0.08968028913527537, -0.903992079888195, -0.08968028913527537, 0.1114034542194284, -0.1420055490952354, 0.11140345421942845, -0.1420055490952354, 0.49928483909803145, -1.031860401303775, 0.49928483909803145, -1.031860401303775, -0.25021332122685536, -0.23430348924020267, -0.2502133212268553, -0.23430348924020258, 0.45788605189844944, 0.008986832993373578, 0.45788605189844944, 0.008986832993373583, 0.9922986143818168, -0.3970601247358978, 0.9922986143818171, -0.3970601247358978, 0.3242247399299542, 0.00883592005445788, 0.3242247399299542, 0.008835920054457881, 0.6104748391149722, -0.1588370496187479, 0.6104748391149722, -0.15883704961874784, -0.2328772934092499, -0.28654852459626834, -0.23287729340924987, -0.28654852459626823, 0.2591579326588679, -0.48250620169929226, 0.2591579326588679, -0.4825062016992922, 0.030769057057074042, -0.6677902182695195, 0.030769057057074042, -0.6677902182695192, 0.5724668628416123, 0.17684659209108886, 0.5724668628416124, 0.17684659209108886, -0.1936816938025718, 0.017884183939394893, -0.19368169380257177, 0.017884183939394897, 0.3927424946727771, -0.3589320240798228, 0.3927424946727773, -0.35893202407982266, -0.13217719866296695, 0.4509072577920714, -0.13217719866296687, 0.4509072577920715, 0.7771200989698435, 0.07094000492318109, 0.7771200989698438, 0.07094000492318112, -0.043208921594939775, -0.7058014850795868, -0.043208921594939755, -0.7058014850795865, -0.44161734737621083, 0.17508260808335738, -0.44161734737621083, 0.17508260808335738, 0.3111521947954433, 0.5211230285003844, 0.3111521947954433, 0.5211230285003846, -0.5089025606249975, -0.08897969566205755, -0.5089025606249975, -0.08897969566205753, -0.785274533858358, 0.2966023384405856, -0.785274533858358, 0.2966023384405857, 0.13643734685972797, -0.5487534801505365, 0.136437346859728, -0.5487534801505362, -0.5113536157192956, -0.38818343681854633, -0.5113536157192953, -0.3881834368185463, 0.6482527388360249, -0.3660801422494009, 0.6482527388360252, -0.3660801422494007, 0.1219550825441264, 0.2636220365395331, 0.12195508254412644, 0.2636220365395332, 0.830646565838305, 0.05595258169938715, 0.8306465658383052, 0.055952581699387154, 0.02087272912166732, -0.2757601788166507, 0.02087272912166733, -0.2757601788166507, -0.8969757534742673, -1.0096320440536182, -0.8969757534742671, -1.0096320440536182, 0.281470556211261, -0.5392051870077439, 0.281470556211261, -0.5392051870077438, 0.09939015666169382, -0.0010699511947921958, 0.09939015666169386, -0.0010699511947921952, -0.002256115172019346, -0.04020319566150099, -0.0022561151720193458, -0.04020319566150097, 0.4504785560293585, 0.373102472756903, 0.4504785560293585, 0.3731024727569031, 0.5231672603524817, 0.16985255790851625, 0.5231672603524821, 0.16985255790851628, -0.7514640400004967, 0.07080018087746165, -0.7514640400004965, 0.07080018087746165, 0.13303832542382837, 0.2602273203264872, 0.1330383254238284, 0.2602273203264874, 0.19343395931079577, -0.5502548672222486, 0.1934339593107958, -0.5502548672222483, -0.20823169078587966, -0.925945416171643, -0.20823169078587964, -0.925945416171643, -1.0354112179615744, 0.9009086420084467, -1.035411217961574, 0.9009086420084467, -0.13833287790394402, 0.33595123313495734, -0.13833287790394397, 0.3359512331349575, -0.48681401106341476, 0.012840401303908289, -0.4868140110634147, 0.012840401303908292, -0.38580806564875847, -0.3414309718415358, -0.3858080656487583, -0.3414309718415357, -0.387387928447792, 0.3363647167396555, -0.387387928447792, 0.3363647167396555, -0.7289577885281368, 0.11000344782305926, -0.7289577885281364, 0.11000344782305929, 0.5996652640170703, -0.3788676471009784, 0.5996652640170704, -0.37886764710097826, 0.1184108904136601, -0.36481788339618465, 0.11841089041366011, -0.36481788339618465, -0.030883796635844396, -0.2470002368704879, -0.030883796635844393, -0.24700023687048783, 0.003754694361758959, -0.19869298401291166, 0.0037546943617589594, -0.1986929840129116, 0.11693502055240339, 0.2098964093295748, 0.11693502055240342, 0.20989640932957487, -0.44372931923544234, 0.056472315155220026, -0.44372931923544234, 0.05647231515522005, -0.2835673309912712, -0.5631986234801009, -0.2835673309912712, -0.5631986234801006, 0.6006827467154858, -0.5932750105917384, 0.6006827467154859, -0.593275010591738, 0.24363277450292076, -0.14517064380485928, 0.24363277450292084, -0.14517064380485925, -0.4381173292277971, 0.8515765445495456, -0.4381173292277971, 0.8515765445495457, -0.4772264554892779, -0.4558040067081244, -0.4772264554892779, -0.4558040067081244, 0.42511520260261526, -0.11760098022868892, 0.4251152026026154, -0.11760098022868892, -0.317536469473846, -0.6047699984659938, -0.31753646947384584, -0.6047699984659937, -0.47946248289928994, -0.6870741625598951, -0.47946248289928994, -0.6870741625598947, 0.24756054302633185, 0.738575212829874, 0.24756054302633188, 0.738575212829874, 0.30991707565082616, -0.1730076242522987, 0.3099170756508263, -0.17300762425229868, 0.1762415438802143, -0.45603299469545666, 0.17624154388021437, -0.4560329946954566, -0.5684090790521096, -0.5323520385817601, -0.5684090790521092, -0.5323520385817597, 1.1773067064626908, -0.31618798230516987, 1.177306706462691, -0.3161879823051697, -0.2853416740347503, -0.7541701445620144, -0.28534167403475025, -0.7541701445620143, -0.3324739283651593, -0.041138670378205386, -0.33247392836515915, -0.041138670378205386, 1.2664180977863824, -0.7401911722318033, 1.2664180977863828, -0.740191172231803, 0.4182693143279388, -0.7039334975576141, 0.41826931432793885, -0.703933497557614, 0.3813359912592416, -1.0453256669790556, 0.3813359912592416, -1.0453256669790554, 0.6509129030314083, -0.5412696201327558, 0.6509129030314084, -0.5412696201327558, 0.12018094767199916, 0.5279211204926886, 0.12018094767199916, 0.5279211204926887, -0.45305717081196895, 0.008198588994697165, -0.45305717081196883, 0.008198588994697166, 1.1671283999119613, -0.15065449704305311, 1.167128399911962, -0.1506544970430531, -0.9008096320814036, 0.1402761647761295, -0.9008096320814036, 0.14027616477612953, -0.33154219658246964, 0.2612070104089204, -0.3315421965824696, 0.2612070104089204, -0.03280139984795011, -0.46647401981355685, -0.032801399847950094, -0.46647401981355685, 0.01502591710973531, -0.5159959791954403, 0.015025917109735313, -0.51599597919544, 0.08126445056757484, -0.059451961687364746, 0.08126445056757486, -0.05945196168736473, -0.4257412994811337, -0.20546840486340784, -0.4257412994811336, -0.20546840486340776, 0.38799639318217627, 0.3512270928822726, 0.3879963931821764, 0.35122709288227266, 0.21154693848150546, -0.03634275654418231, 0.21154693848150552, -0.0363427565441823, -0.23511045964865424, -0.3182820554745927, -0.23511045964865424, -0.3182820554745926, -0.27930734350964126, -0.34019779603069944, -0.27930734350964115, -0.3401977960306993, -0.7191434211894179, 0.018581718879366438, -0.7191434211894179, 0.018581718879366448, -0.020348708221664874, -0.11541476308320475, -0.020348708221664864, -0.11541476308320471, -0.869130537954744, 0.5168791425703672, -0.8691305379547439, 0.5168791425703672, -0.30797478551715907, 0.16894312777393505, -0.30797478551715896, 0.16894312777393514, -0.3412253953512523, -0.13703919671643483, -0.3412253953512523, -0.1370391967164348, -0.2363788997551411, 0.020160959823633195, -0.2363788997551411, 0.020160959823633202, -1.1342573157600304, -1.0490903515949865, -1.1342573157600302, -1.0490903515949863, -0.7951801524174422, -0.39048765852721024, -0.7951801524174421, -0.39048765852721024, -0.37682393173602985, -0.7154876526440125, -0.37682393173602974, -0.7154876526440123, -0.7261698499159233, 0.25576182656428276, -0.7261698499159229, 0.25576182656428287, 0.6047122068958138, 0.3531321759458359, 0.604712206895814, 0.35313217594583596, -0.3347865534686024, -0.44639370766792674, -0.3347865534686024, -0.4463937076679267, -0.3162737402922597, -0.6054254978296343, -0.3162737402922597, -0.6054254978296342, -0.38296113359720985, 1.055727844318872, -0.38296113359720985, 1.0557278443188722, -0.002541168924166004, -0.08959542143473792, -0.0025411689241660036, -0.08959542143473788, -0.46847678028199197, 0.3128229066138286, -0.4684767802819919, 0.3128229066138288, -0.7474510887594696, -0.11273520921655422, -0.7474510887594695, -0.11273520921655422, -0.10138857243233154, 0.6540514477632215, -0.10138857243233154, 0.6540514477632217, 0.7025815823095183, -0.6472293123262207, 0.7025815823095184, -0.6472293123262207, 0.7918249248447928, -0.19424553454596438, 0.7918249248447932, -0.19424553454596438, 0.054665259285737594, -0.1426160884627486, 0.05466525928573761, -0.14261608846274854, 0.8678958225451003, 0.7680573370722297, 0.8678958225451004, 0.7680573370722298, 0.2527320686719843, -0.10300747956510839, 0.25273206867198444, -0.10300747956510836, 0.013030931888632663, 0.2996259196764839, 0.013030931888632665, 0.2996259196764839, 1.2101948699429645, 0.7680276029628541, 1.210194869942965, 0.7680276029628543, 0.001739080834353146, 0.7050842932559666, 0.0017390808343531463, 0.7050842932559666, 0.7920805263720672, -0.5649631474553106, 0.7920805263720672, -0.5649631474553105, 0.25575043599568525, 0.0889317006762374, 0.25575043599568525, 0.08893170067623742, 0.09261316731698108, 0.2703067174076892, 0.0926131673169811, 0.27030671740768925, -0.5747802180771169, 0.08613851106223658, -0.5747802180771168, 0.08613851106223662, 0.40507673833837643, -0.8945358512704514, 0.40507673833837643, -0.8945358512704511, 0.3856111747477545, -0.11976774680260635, 0.3856111747477546, -0.11976774680260632, -0.25578702556512617, 0.3677566511805598, -0.255787025565126, 0.36775665118055983, -0.20976738975410314, 0.6671667928732408, -0.20976738975410314, 0.6671667928732408, -0.21007992057543357, 0.11101431938197523, -0.21007992057543348, 0.11101431938197523, -0.5538419739084758, -0.050566470413442005, -0.5538419739084757, -0.05056647041344199, -0.26983745787555147, -0.005254721629673997, -0.2698374578755514, -0.0052547216296739965, -0.31654388864740896, 0.4356887820490702, -0.3165438886474089, 0.43568878204907036, -0.6124922582532396, -0.22656761299178974, -0.6124922582532395, -0.22656761299178974, 0.5136728866074527, -0.14672923625352396, 0.513672886607453, -0.14672923625352388, -0.06100014188022765, -0.07483055132359873, -0.06100014188022765, -0.07483055132359868, 0.0632389321030824, -0.3727037315430909, 0.06323893210308244, -0.3727037315430909, -0.6239765829480394, -0.43378186506793615, -0.6239765829480394, -0.43378186506793603, -0.2962023614106011, -0.24082492622254642, -0.296202361410601, -0.24082492622254636, -0.08363974045743232, 0.4635673337808054, -0.08363974045743229, 0.4635673337808054, -0.07869730556773968, 0.7594146318238462, -0.07869730556773967, 0.7594146318238463, 0.559161552723403, 0.26005051714491845, 0.5591615527234033, 0.2600505171449186, 0.009099193447173748, -0.8925628969298484, 0.00909919344717375, -0.892562896929848, -0.01551647656911137, -0.38885814801603924, -0.015516476569111365, -0.38885814801603924, -0.01567035614455939, -0.3579485826040038, -0.015670356144559385, -0.35794858260400375, 0.446781462990565, -0.052239411468506664, 0.446781462990565, -0.05223941146850665, 1.0710389841912518, -0.2731132034289364, 1.0710389841912522, -0.2731132034289364, 0.23533790163003582, -0.23476194158747798, 0.23533790163003585, -0.23476194158747793, 0.07915424936926652, 0.6036539628377416, 0.07915424936926652, 0.6036539628377419, 0.6311044368999582, -0.6562564634414947, 0.6311044368999585, -0.6562564634414947, -0.21077148265812098, 0.032523815759867236, -0.2107714826581209, 0.03252381575986725, -0.7231240597670221, -0.006544627251553192, -0.7231240597670221, -0.006544627251553192, -0.08060584759784664, 0.13336777305165762, -0.08060584759784663, 0.13336777305165762, 0.48597827619774187, -0.6069162101181359, 0.48597827619774203, -0.6069162101181359, -0.4507483055292626, 0.19434862886898324, -0.4507483055292625, 0.19434862886898324, 0.2827195867383647, -0.22519487430374507, 0.2827195867383647, -0.22519487430374502, -0.8215093346304647, -0.03268014435976413, -0.8215093346304647, -0.03268014435976413, -0.11933763497114419, 0.25235131805383626, -0.11933763497114419, 0.25235131805383626, -0.050641541900826315, -0.05481336786080909, -0.05064154190082631, -0.05481336786080908, 0.37639163137503584, -0.04913023720926801, 0.37639163137503595, -0.049130237209268006, 0.2754899163868257, -1.2892018379461803, 0.27548991638682585, -1.28920183794618, 0.19113786193208002, -0.49992907513642937, 0.1911378619320801, -0.4999290751364293, -0.18408107881733532, -0.6738283284096425, -0.18408107881733524, -0.6738283284096425, 0.26736586776080096, 0.35645201936711196, 0.2673658677608011, 0.35645201936711196, 1.1765511302564113, -0.5480893596413949, 1.176551130256412, -0.5480893596413949, 1.1542398998705217, -0.3147952918363603, 1.1542398998705217, -0.3147952918363603, -0.6689853024562176, 0.8040377543458188, -0.6689853024562172, 0.804037754345819, 0.24120212235388105, -0.07423471553787372, 0.2412021223538811, -0.0742347155378737, 0.5689391732853385, -0.4334628652354342, 0.5689391732853388, -0.43346286523543415, -0.4229071860412019, 0.11827577249881677, -0.4229071860412019, 0.11827577249881677, -0.5721332694193333, 0.26812444739865027, -0.5721332694193333, 0.26812444739865043, -0.14648803653271852, 0.4305316791577641, -0.1464880365327185, 0.43053167915776425, 0.05374623984152754, -0.4459959249147729, 0.053746239841527564, -0.4459959249147729, 0.5896530144495327, 0.07735649659442079, 0.589653014449533, 0.07735649659442081, -0.25257596915203095, -0.1831343633500895, -0.2525759691520309, -0.18313436335008942, 0.6519199000082152, 0.8113502122689806, 0.6519199000082153, 0.811350212268981, -0.20987680281715365, 0.31018961232143716, -0.2098768028171536, 0.3101896123214372, 0.488852615545995, -0.7694857263920457, 0.488852615545995, -0.7694857263920457, 0.32498664525642773, 0.35466894818618966, 0.3249866452564279, 0.3546689481861898, -0.21867254773101694, 0.33653237135631914, -0.21867254773101685, 0.3365323713563192, -0.1628632057456908, 0.12513912098254698, -0.16286320574569077, 0.12513912098254704, -0.2482127546806861, 0.054592620932045616, -0.24821275468068604, 0.05459262093204564, 0.19972864932719311, 0.48470032915534, 0.19972864932719311, 0.4847003291553401, 0.5194203708908046, 0.6086898891039105, 0.519420370890805, 0.6086898891039109, 0.19766219439600413, -0.624494348335875, 0.1976621943960042, -0.6244943483358748, -0.6659766058933296, 0.5642507949642299, -0.6659766058933294, 0.56425079496423, 0.6380303702196312, 0.7911458327140173, 0.6380303702196312, 0.7911458327140173, -0.2639580944341406, 1.0973674142268384, -0.26395809443414053, 1.0973674142268388, -0.013043068475538544, -0.18048505417693753, -0.013043068475538539, -0.1804850541769375, -0.6177459783187123, -0.2779905668540201, -0.6177459783187123, -0.27799056685401996, 0.6541020344580163, 0.582124792529954, 0.6541020344580166, 0.5821247925299543, -1.0384774049322054, 0.8009193618277922, -1.0384774049322048, 0.8009193618277922, -0.1554306169575903, 0.44885645072316704, -0.15543061695759022, 0.4488564507231671, -0.21901225075291414, 0.029572470395186623, -0.21901225075291408, 0.029572470395186626, 0.06665349581693292, 0.2278463140029154, 0.06665349581693296, 0.22784631400291547, -0.18730209014152358, -0.44204961843797247, -0.1873020901415235, -0.44204961843797247, -0.8954194222707068, -0.09622762051569644, -0.8954194222707068, -0.09622762051569644, 0.6876813467148475, -0.1006745035590906, 0.6876813467148476, -0.10067450355909059, 0.8020144882556199, -0.4557444532553835, 0.80201448825562, -0.4557444532553834, 0.11678579588295551, 0.4778013596576872, 0.11678579588295553, 0.4778013596576872, -0.6173779479953273, -0.1463086195272349, -0.6173779479953271, -0.1463086195272348, 0.04109570275886973, -0.38022576288843984, 0.04109570275886973, -0.3802257628884398, 0.8314003498756972, -0.48166469434786263, 0.8314003498756976, -0.4816646943478625, -0.3417449594665635, 0.2351852756985343, -0.34174495946656336, 0.23518527569853434, -0.747231864230736, -0.05533196936496787, -0.7472318642307357, -0.055331969364967856, 0.44786515872763016, -0.8581662077619436, 0.4478651587276303, -0.8581662077619435, 0.2394196493059546, 0.5685962507505915, 0.23941964930595466, 0.5685962507505915, -0.47370747024486054, -0.518217306207919, -0.4737074702448605, -0.5182173062079186, -0.24686466238928517, 0.5140980999371543, -0.24686466238928517, 0.5140980999371544, 0.4465869335283311, -0.37822156772624715, 0.4465869335283311, -0.378221567726247, 0.7216840280411014, -0.12155234552799939, 0.7216840280411017, -0.12155234552799934, 0.015204864396908546, 0.6376683618342354, 0.015204864396908548, 0.6376683618342357, -0.42393694982300156, -0.5218089477315881, -0.42393694982300145, -0.5218089477315878, 0.07415078821601045, 0.6371956908817733, 0.07415078821601047, 0.6371956908817734, -0.1903574628038755, -0.38684400671343444, -0.19035746280387544, -0.38684400671343444, -0.3773559131237457, 0.0068579608273421355, -0.3773559131237457, 0.006857960827342137, 0.08501466839094085, 0.27421860297639405, 0.08501466839094089, 0.2742186029763941, 1.3703190609240201, -0.6705242349995242, 1.3703190609240201, -0.6705242349995238, 0.22067502222484947, -0.42972719575427676, 0.22067502222484955, -0.4297271957542766, 0.4496324731373458, -0.5997904924904096, 0.44963247313734583, -0.5997904924904094, 0.4606769016215748, -0.4028663766293615, 0.4606769016215748, -0.4028663766293614, 0.20461881450521396, 0.23845839738985905, 0.20461881450521396, 0.2384583973898591, -0.177021903697815, 0.0017472361069717779, -0.17702190369781493, 0.0017472361069717785, 0.33088666738271627, 0.39635242461181414, 0.33088666738271644, 0.39635242461181425, -0.5126793030962896, -0.9816818891160128, -0.5126793030962894, -0.9816818891160127, -0.20315580021343643, 0.25993483522132416, -0.2031558002134364, 0.2599348352213242, 0.01157315314252727, -0.0752286580183012, 0.011573153142527272, -0.07522865801830117, -0.2122874953702656, 1.0455265018271471, -0.2122874953702656, 1.0455265018271478, -0.4118959539781374, 0.2565463745780656, -0.41189595397813733, 0.2565463745780657, -0.40504807761153394, -0.826767279687959, -0.40504807761153383, -0.8267672796879587, 0.8728370056581523, -0.8489146211330629, 0.8728370056581523, -0.8489146211330626, -0.15484731030271964, 0.2978543674333216, -0.15484731030271962, 0.2978543674333217, 0.9598395979151622, -0.021475535817715843, 0.9598395979151622, -0.021475535817715833, -0.3813769756912948, 0.7192828208488169, -0.38137697569129464, 0.719282820848817, 0.21951101473819934, 0.6480843500744788, 0.21951101473819934, 0.6480843500744791, -0.3113427744080721, 0.045948715073330315, -0.31134277440807195, 0.045948715073330336, -0.16009981684527497, -0.17250123317199526, -0.16009981684527497, -0.17250123317199526, 0.25568807750253153, 0.30423782531372767, 0.2556880775025317, 0.30423782531372784, 0.2534978588720535, 0.41258202395216825, 0.25349785887205356, 0.4125820239521684, -0.22823188438717018, 0.3555909158613313, -0.22823188438717018, 0.3555909158613314, -0.043847734475191566, 0.546988883272136, -0.04384773447519155, 0.5469888832721362, 0.0022848127328267687, 0.16581911916150355, 0.0022848127328267695, 0.16581911916150358, -0.9664510167365821, 0.5772556019222926, -0.9664510167365818, 0.5772556019222929, 0.19331577714046103, 0.16819098929912168, 0.1933157771404611, 0.16819098929912168, 0.880938028512706, 1.3996876457175011, 0.8809380285127063, 1.3996876457175018, -0.6403207225525454, 0.2297596920614577, -0.640320722552545, 0.22975969206145774, -0.926993144927124, -0.7404608887419831, -0.9269931449271237, -0.7404608887419828, -0.30368277421537726, -0.5055446699316368, -0.3036827742153772, -0.5055446699316366, 0.5466694604144853, 0.07004761038909013, 0.5466694604144854, 0.07004761038909016, 0.25500851421300097, -0.29367076034138706, 0.25500851421300114, -0.29367076034138695, 0.15138727668563495, -0.0049418965549759275, 0.151387276685635, -0.004941896554975927, -0.43887856303510187, 0.8136477342030863, -0.4388785630351018, 0.8136477342030866, -0.33880265875092413, -0.31551224415527107, -0.33880265875092397, -0.315512244155271, 1.377423681456482, 0.012704561359672462, 1.377423681456482, 0.012704561359672462, -0.041263422421853435, 0.4035844851267748, -0.041263422421853414, 0.40358448512677497, -0.08610165644909173, -0.7986737010728233, -0.08610165644909172, -0.7986737010728232, 0.3836918938530838, 0.8390085156051033, 0.38369189385308383, 0.8390085156051033, -0.17307936456124118, -0.06474709047756155, -0.1730793645612411, -0.06474709047756153, -0.02753475823767776, -0.15870621273858665, -0.02753475823767775, -0.15870621273858657, -0.5116996522331295, -0.4553457116638264, -0.5116996522331294, -0.45534571166382637, 0.6086269804673172, 0.015815755110900165, 0.6086269804673176, 0.015815755110900165, -0.3066696359213093, -0.6490796718967194, -0.3066696359213093, -0.6490796718967194, 0.2573582808012723, 0.49429943061451787, 0.25735828080127243, 0.4942994306145179, -0.5573569025227104, 0.10864971359925568, -0.5573569025227101, 0.1086497135992557, 0.10100854569812368, -0.5775400700305715, 0.10100854569812368, -0.5775400700305712, 0.16011849083924728, -0.5182501761924749, 0.1601184908392473, -0.5182501761924749, 1.1626364195660153, -0.027141868869618918, 1.162636419566016, -0.027141868869618915, -0.45286020053725284, 0.46618578082394724, -0.4528602005372528, 0.4661857808239473, 0.32258327609642495, -0.2102016160014837, 0.3225832760964251, -0.21020161600148368, -0.4469041249092892, -0.30385833257152894, -0.4469041249092891, -0.30385833257152894, 0.8377224062973287, -0.5225876068528582, 0.8377224062973289, -0.5225876068528581, -0.35063350958529577, -0.44521824304962737, -0.3506335095852957, -0.44521824304962726, 0.042917945172412694, -0.2699072536318396, 0.0429179451724127, -0.2699072536318395, 0.28617439894992625, -0.6241441143108587, 0.28617439894992625, -0.6241441143108584, -0.21331655993940007, 1.1315954154549954, -0.21331655993940002, 1.1315954154549959, -0.7071603986591413, -0.0587365030909921, -0.7071603986591409, -0.0587365030909921, -0.43104678259786616, -0.4031905103539523, -0.4310467825978661, -0.40319051035395215, 0.479647329346727, -0.6208557999362405, 0.47964732934672716, -0.6208557999362404, -0.27104983788326825, 0.005338803231299233, -0.2710498378832682, 0.0053388032312992354, -0.0041329173810210895, 0.3935166528530436, -0.004132917381021089, 0.39351665285304366 };
validate(coords2);
}
|
; A099571: Sum C(n-k+3,k), k=0..floor(n/2).
; 1,1,5,6,17,23,50,73,138,211,370,581,979,1560,2575,4135,6755,10890,17700,28590,46356,74946,121380,196326,317797,514123,832025,1346148,2178293,3524441,5702870,9227311,14930334,24157645,39088150,63245795
lpb $0
mov $2,$0
sub $0,1
seq $2,54451 ; Third column of triangle A054450 (partial row sums of unsigned Chebyshev triangle A049310).
add $1,$2
mov $3,$2
min $3,1
sub $0,$3
lpe
add $1,1
mov $0,$1
|
;
; Z88 Graphics Functions - Small C+ stubs
;
; Written around the Interlogic Standard Library
;
; Stubs Written by D Morris - 30/9/98
;
; ----- void __CALLEE__ setpos(int x2, int y2)
;
; $Id: w_setpos_callee.asm $
;
SECTION code_graphics
PUBLIC setpos_callee
PUBLIC _setpos_callee
PUBLIC ASMDISP_SETPOS_CALLEE
EXTERN w_setxy
.setpos_callee
._setpos_callee
pop af ; ret addr
pop de
pop hl
push af ; ret addr
.asmentry
jp w_setxy
DEFC ASMDISP_SETPOS_CALLEE = # asmentry - setpos_callee
|
;******************************************************************************
;* x86-optimized horizontal line scaling functions
;* Copyright (c) 2011 Ronald S. Bultje <rsbultje@gmail.com>
;*
;* This file is part of FFmpeg.
;*
;* FFmpeg is free software; you can redistribute it and/or
;* modify it under the terms of the GNU Lesser General Public
;* License as published by the Free Software Foundation; either
;* version 2.1 of the License, or (at your option) any later version.
;*
;* FFmpeg is distributed in the hope that it will be useful,
;* but WITHOUT ANY WARRANTY; without even the implied warranty of
;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;* Lesser General Public License for more details.
;*
;* You should have received a copy of the GNU Lesser General Public
;* License along with FFmpeg; if not, write to the Free Software
;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;******************************************************************************
%include "libavutil/x86/x86util.asm"
SECTION_RODATA
max_19bit_int: times 4 dd 0x7ffff
max_19bit_flt: times 4 dd 524287.0
minshort: times 8 dw 0x8000
unicoeff: times 4 dd 0x20000000
SECTION .text
;-----------------------------------------------------------------------------
; horizontal line scaling
;
; void hscale<source_width>to<intermediate_nbits>_<filterSize>_<opt>
; (SwsContext *c, int{16,32}_t *dst,
; int dstW, const uint{8,16}_t *src,
; const int16_t *filter,
; const int32_t *filterPos, int filterSize);
;
; Scale one horizontal line. Input is either 8-bits width or 16-bits width
; ($source_width can be either 8, 9, 10 or 16, difference is whether we have to
; downscale before multiplying). Filter is 14-bits. Output is either 15bits
; (in int16_t) or 19bits (in int32_t), as given in $intermediate_nbits. Each
; output pixel is generated from $filterSize input pixels, the position of
; the first pixel is given in filterPos[nOutputPixel].
;-----------------------------------------------------------------------------
; SCALE_FUNC source_width, intermediate_nbits, filtersize, filtersuffix, n_args, n_xmm
%macro SCALE_FUNC 6
%ifnidn %3, X
cglobal hscale%1to%2_%4, %5, 7, %6, pos0, dst, w, src, filter, fltpos, pos1
%else
cglobal hscale%1to%2_%4, %5, 10, %6, pos0, dst, w, srcmem, filter, fltpos, fltsize
%endif
%if ARCH_X86_64
movsxd wq, wd
%define mov32 movsxd
%else ; x86-32
%define mov32 mov
%endif ; x86-64
%if %2 == 19
%if mmsize == 8 ; mmx
mova m2, [max_19bit_int]
%elif cpuflag(sse4)
mova m2, [max_19bit_int]
%else ; ssse3/sse2
mova m2, [max_19bit_flt]
%endif ; mmx/sse2/ssse3/sse4
%endif ; %2 == 19
%if %1 == 16
mova m6, [minshort]
mova m7, [unicoeff]
%elif %1 == 8
pxor m3, m3
%endif ; %1 == 8/16
%if %1 == 8
%define movlh movd
%define movbh movh
%define srcmul 1
%else ; %1 == 9-16
%define movlh movq
%define movbh movu
%define srcmul 2
%endif ; %1 == 8/9-16
%ifnidn %3, X
; setup loop
%if %3 == 8
shl wq, 1 ; this allows *16 (i.e. now *8) in lea instructions for the 8-tap filter
%define wshr 1
%else ; %3 == 4
%define wshr 0
%endif ; %3 == 8
lea filterq, [filterq+wq*8]
%if %2 == 15
lea dstq, [dstq+wq*(2>>wshr)]
%else ; %2 == 19
lea dstq, [dstq+wq*(4>>wshr)]
%endif ; %2 == 15/19
lea fltposq, [fltposq+wq*(4>>wshr)]
neg wq
.loop:
%if %3 == 4 ; filterSize == 4 scaling
; load 2x4 or 4x4 source pixels into m0/m1
mov32 pos0q, dword [fltposq+wq*4+ 0] ; filterPos[0]
mov32 pos1q, dword [fltposq+wq*4+ 4] ; filterPos[1]
movlh m0, [srcq+pos0q*srcmul] ; src[filterPos[0] + {0,1,2,3}]
%if mmsize == 8
movlh m1, [srcq+pos1q*srcmul] ; src[filterPos[1] + {0,1,2,3}]
%else ; mmsize == 16
%if %1 > 8
movhps m0, [srcq+pos1q*srcmul] ; src[filterPos[1] + {0,1,2,3}]
%else ; %1 == 8
movd m4, [srcq+pos1q*srcmul] ; src[filterPos[1] + {0,1,2,3}]
%endif
mov32 pos0q, dword [fltposq+wq*4+ 8] ; filterPos[2]
mov32 pos1q, dword [fltposq+wq*4+12] ; filterPos[3]
movlh m1, [srcq+pos0q*srcmul] ; src[filterPos[2] + {0,1,2,3}]
%if %1 > 8
movhps m1, [srcq+pos1q*srcmul] ; src[filterPos[3] + {0,1,2,3}]
%else ; %1 == 8
movd m5, [srcq+pos1q*srcmul] ; src[filterPos[3] + {0,1,2,3}]
punpckldq m0, m4
punpckldq m1, m5
%endif ; %1 == 8
%endif ; mmsize == 8/16
%if %1 == 8
punpcklbw m0, m3 ; byte -> word
punpcklbw m1, m3 ; byte -> word
%endif ; %1 == 8
; multiply with filter coefficients
%if %1 == 16 ; pmaddwd needs signed adds, so this moves unsigned -> signed, we'll
; add back 0x8000 * sum(coeffs) after the horizontal add
psubw m0, m6
psubw m1, m6
%endif ; %1 == 16
pmaddwd m0, [filterq+wq*8+mmsize*0] ; *= filter[{0,1,..,6,7}]
pmaddwd m1, [filterq+wq*8+mmsize*1] ; *= filter[{8,9,..,14,15}]
; add up horizontally (4 srcpix * 4 coefficients -> 1 dstpix)
%if mmsize == 8 ; mmx
movq m4, m0
punpckldq m0, m1
punpckhdq m4, m1
paddd m0, m4
%elif notcpuflag(ssse3) ; sse2
mova m4, m0
shufps m0, m1, 10001000b
shufps m4, m1, 11011101b
paddd m0, m4
%else ; ssse3/sse4
phaddd m0, m1 ; filter[{ 0, 1, 2, 3}]*src[filterPos[0]+{0,1,2,3}],
; filter[{ 4, 5, 6, 7}]*src[filterPos[1]+{0,1,2,3}],
; filter[{ 8, 9,10,11}]*src[filterPos[2]+{0,1,2,3}],
; filter[{12,13,14,15}]*src[filterPos[3]+{0,1,2,3}]
%endif ; mmx/sse2/ssse3/sse4
%else ; %3 == 8, i.e. filterSize == 8 scaling
; load 2x8 or 4x8 source pixels into m0, m1, m4 and m5
mov32 pos0q, dword [fltposq+wq*2+0] ; filterPos[0]
mov32 pos1q, dword [fltposq+wq*2+4] ; filterPos[1]
movbh m0, [srcq+ pos0q *srcmul] ; src[filterPos[0] + {0,1,2,3,4,5,6,7}]
%if mmsize == 8
movbh m1, [srcq+(pos0q+4)*srcmul] ; src[filterPos[0] + {4,5,6,7}]
movbh m4, [srcq+ pos1q *srcmul] ; src[filterPos[1] + {0,1,2,3}]
movbh m5, [srcq+(pos1q+4)*srcmul] ; src[filterPos[1] + {4,5,6,7}]
%else ; mmsize == 16
movbh m1, [srcq+ pos1q *srcmul] ; src[filterPos[1] + {0,1,2,3,4,5,6,7}]
mov32 pos0q, dword [fltposq+wq*2+8] ; filterPos[2]
mov32 pos1q, dword [fltposq+wq*2+12] ; filterPos[3]
movbh m4, [srcq+ pos0q *srcmul] ; src[filterPos[2] + {0,1,2,3,4,5,6,7}]
movbh m5, [srcq+ pos1q *srcmul] ; src[filterPos[3] + {0,1,2,3,4,5,6,7}]
%endif ; mmsize == 8/16
%if %1 == 8
punpcklbw m0, m3 ; byte -> word
punpcklbw m1, m3 ; byte -> word
punpcklbw m4, m3 ; byte -> word
punpcklbw m5, m3 ; byte -> word
%endif ; %1 == 8
; multiply
%if %1 == 16 ; pmaddwd needs signed adds, so this moves unsigned -> signed, we'll
; add back 0x8000 * sum(coeffs) after the horizontal add
psubw m0, m6
psubw m1, m6
psubw m4, m6
psubw m5, m6
%endif ; %1 == 16
pmaddwd m0, [filterq+wq*8+mmsize*0] ; *= filter[{0,1,..,6,7}]
pmaddwd m1, [filterq+wq*8+mmsize*1] ; *= filter[{8,9,..,14,15}]
pmaddwd m4, [filterq+wq*8+mmsize*2] ; *= filter[{16,17,..,22,23}]
pmaddwd m5, [filterq+wq*8+mmsize*3] ; *= filter[{24,25,..,30,31}]
; add up horizontally (8 srcpix * 8 coefficients -> 1 dstpix)
%if mmsize == 8
paddd m0, m1
paddd m4, m5
movq m1, m0
punpckldq m0, m4
punpckhdq m1, m4
paddd m0, m1
%elif notcpuflag(ssse3) ; sse2
%if %1 == 8
%define mex m6
%else
%define mex m3
%endif
; emulate horizontal add as transpose + vertical add
mova mex, m0
punpckldq m0, m1
punpckhdq mex, m1
paddd m0, mex
mova m1, m4
punpckldq m4, m5
punpckhdq m1, m5
paddd m4, m1
mova m1, m0
punpcklqdq m0, m4
punpckhqdq m1, m4
paddd m0, m1
%else ; ssse3/sse4
; FIXME if we rearrange the filter in pairs of 4, we can
; load pixels likewise and use 2 x paddd + phaddd instead
; of 3 x phaddd here, faster on older cpus
phaddd m0, m1
phaddd m4, m5
phaddd m0, m4 ; filter[{ 0, 1,..., 6, 7}]*src[filterPos[0]+{0,1,...,6,7}],
; filter[{ 8, 9,...,14,15}]*src[filterPos[1]+{0,1,...,6,7}],
; filter[{16,17,...,22,23}]*src[filterPos[2]+{0,1,...,6,7}],
; filter[{24,25,...,30,31}]*src[filterPos[3]+{0,1,...,6,7}]
%endif ; mmx/sse2/ssse3/sse4
%endif ; %3 == 4/8
%else ; %3 == X, i.e. any filterSize scaling
%ifidn %4, X4
%define dlt 4
%else ; %4 == X || %4 == X8
%define dlt 0
%endif ; %4 ==/!= X4
%if ARCH_X86_64
%define srcq r8
%define pos1q r7
%define srcendq r9
movsxd fltsizeq, fltsized ; filterSize
lea srcendq, [srcmemq+(fltsizeq-dlt)*srcmul] ; &src[filterSize&~4]
%else ; x86-32
%define srcq srcmemq
%define pos1q dstq
%define srcendq r6m
lea pos0q, [srcmemq+(fltsizeq-dlt)*srcmul] ; &src[filterSize&~4]
mov srcendq, pos0q
%endif ; x86-32/64
lea fltposq, [fltposq+wq*4]
%if %2 == 15
lea dstq, [dstq+wq*2]
%else ; %2 == 19
lea dstq, [dstq+wq*4]
%endif ; %2 == 15/19
movifnidn dstmp, dstq
neg wq
.loop:
mov32 pos0q, dword [fltposq+wq*4+0] ; filterPos[0]
mov32 pos1q, dword [fltposq+wq*4+4] ; filterPos[1]
; FIXME maybe do 4px/iteration on x86-64 (x86-32 wouldn't have enough regs)?
pxor m4, m4
pxor m5, m5
mov srcq, srcmemmp
.innerloop:
; load 2x4 (mmx) or 2x8 (sse) source pixels into m0/m1 -> m4/m5
movbh m0, [srcq+ pos0q *srcmul] ; src[filterPos[0] + {0,1,2,3(,4,5,6,7)}]
movbh m1, [srcq+(pos1q+dlt)*srcmul] ; src[filterPos[1] + {0,1,2,3(,4,5,6,7)}]
%if %1 == 8
punpcklbw m0, m3
punpcklbw m1, m3
%endif ; %1 == 8
; multiply
%if %1 == 16 ; pmaddwd needs signed adds, so this moves unsigned -> signed, we'll
; add back 0x8000 * sum(coeffs) after the horizontal add
psubw m0, m6
psubw m1, m6
%endif ; %1 == 16
pmaddwd m0, [filterq] ; filter[{0,1,2,3(,4,5,6,7)}]
pmaddwd m1, [filterq+(fltsizeq+dlt)*2]; filter[filtersize+{0,1,2,3(,4,5,6,7)}]
paddd m4, m0
paddd m5, m1
add filterq, mmsize
add srcq, srcmul*mmsize/2
cmp srcq, srcendq ; while (src += 4) < &src[filterSize]
jl .innerloop
%ifidn %4, X4
mov32 pos1q, dword [fltposq+wq*4+4] ; filterPos[1]
movlh m0, [srcq+ pos0q *srcmul] ; split last 4 srcpx of dstpx[0]
sub pos1q, fltsizeq ; and first 4 srcpx of dstpx[1]
%if %1 > 8
movhps m0, [srcq+(pos1q+dlt)*srcmul]
%else ; %1 == 8
movd m1, [srcq+(pos1q+dlt)*srcmul]
punpckldq m0, m1
%endif ; %1 == 8
%if %1 == 8
punpcklbw m0, m3
%endif ; %1 == 8
%if %1 == 16 ; pmaddwd needs signed adds, so this moves unsigned -> signed, we'll
; add back 0x8000 * sum(coeffs) after the horizontal add
psubw m0, m6
%endif ; %1 == 16
pmaddwd m0, [filterq]
%endif ; %4 == X4
lea filterq, [filterq+(fltsizeq+dlt)*2]
%if mmsize == 8 ; mmx
movq m0, m4
punpckldq m4, m5
punpckhdq m0, m5
paddd m0, m4
%else ; mmsize == 16
%if notcpuflag(ssse3) ; sse2
mova m1, m4
punpcklqdq m4, m5
punpckhqdq m1, m5
paddd m4, m1
%else ; ssse3/sse4
phaddd m4, m5
%endif ; sse2/ssse3/sse4
%ifidn %4, X4
paddd m4, m0
%endif ; %3 == X4
%if notcpuflag(ssse3) ; sse2
pshufd m4, m4, 11011000b
movhlps m0, m4
paddd m0, m4
%else ; ssse3/sse4
phaddd m4, m4
SWAP 0, 4
%endif ; sse2/ssse3/sse4
%endif ; mmsize == 8/16
%endif ; %3 ==/!= X
%if %1 == 16 ; add 0x8000 * sum(coeffs), i.e. back from signed -> unsigned
paddd m0, m7
%endif ; %1 == 16
; clip, store
psrad m0, 14 + %1 - %2
%ifidn %3, X
movifnidn dstq, dstmp
%endif ; %3 == X
%if %2 == 15
packssdw m0, m0
%ifnidn %3, X
movh [dstq+wq*(2>>wshr)], m0
%else ; %3 == X
movd [dstq+wq*2], m0
%endif ; %3 ==/!= X
%else ; %2 == 19
%if mmsize == 8
PMINSD_MMX m0, m2, m4
%elif cpuflag(sse4)
pminsd m0, m2
%else ; sse2/ssse3
cvtdq2ps m0, m0
minps m0, m2
cvtps2dq m0, m0
%endif ; mmx/sse2/ssse3/sse4
%ifnidn %3, X
mova [dstq+wq*(4>>wshr)], m0
%else ; %3 == X
movq [dstq+wq*4], m0
%endif ; %3 ==/!= X
%endif ; %2 == 15/19
%ifnidn %3, X
add wq, (mmsize<<wshr)/4 ; both 8tap and 4tap really only do 4 pixels (or for mmx: 2 pixels)
; per iteration. see "shl wq,1" above as for why we do this
%else ; %3 == X
add wq, 2
%endif ; %3 ==/!= X
jl .loop
REP_RET
%endmacro
; SCALE_FUNCS source_width, intermediate_nbits, n_xmm
%macro SCALE_FUNCS 3
SCALE_FUNC %1, %2, 4, 4, 6, %3
SCALE_FUNC %1, %2, 8, 8, 6, %3
%if mmsize == 8
SCALE_FUNC %1, %2, X, X, 7, %3
%else
SCALE_FUNC %1, %2, X, X4, 7, %3
SCALE_FUNC %1, %2, X, X8, 7, %3
%endif
%endmacro
; SCALE_FUNCS2 8_xmm_args, 9to10_xmm_args, 16_xmm_args
%macro SCALE_FUNCS2 3
%if notcpuflag(sse4)
SCALE_FUNCS 8, 15, %1
SCALE_FUNCS 9, 15, %2
SCALE_FUNCS 10, 15, %2
SCALE_FUNCS 12, 15, %2
SCALE_FUNCS 14, 15, %2
SCALE_FUNCS 16, 15, %3
%endif ; !sse4
SCALE_FUNCS 8, 19, %1
SCALE_FUNCS 9, 19, %2
SCALE_FUNCS 10, 19, %2
SCALE_FUNCS 12, 19, %2
SCALE_FUNCS 14, 19, %2
SCALE_FUNCS 16, 19, %3
%endmacro
%if ARCH_X86_32
INIT_MMX mmx
SCALE_FUNCS2 0, 0, 0
%endif
INIT_XMM sse2
SCALE_FUNCS2 6, 7, 8
INIT_XMM ssse3
SCALE_FUNCS2 6, 6, 8
INIT_XMM sse4
SCALE_FUNCS2 6, 6, 8
|
;------------------------------------------------------------------------------
;
; Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.<BR>
; SPDX-License-Identifier: BSD-2-Clause-Patent
;
; Module Name:
;
; CompareMem.Asm
;
; Abstract:
;
; CompareMem function
;
; Notes:
;
; The following BaseMemoryLib instances contain the same copy of this file:
;
; BaseMemoryLibRepStr
; BaseMemoryLibMmx
; BaseMemoryLibSse2
; BaseMemoryLibOptDxe
; BaseMemoryLibOptPei
;
;------------------------------------------------------------------------------
SECTION .text
;------------------------------------------------------------------------------
; INTN
; EFIAPI
; InternalMemCompareMem (
; IN CONST VOID *DestinationBuffer,
; IN CONST VOID *SourceBuffer,
; IN UINTN Length
; );
;------------------------------------------------------------------------------
global ASM_PFX(InternalMemCompareMem)
ASM_PFX(InternalMemCompareMem):
push esi
push edi
mov esi, [esp + 12]
mov edi, [esp + 16]
mov ecx, [esp + 20]
repe cmpsb
movzx eax, byte [esi - 1]
movzx edx, byte [edi - 1]
sub eax, edx
pop edi
pop esi
ret
|
CUR_ROM_BANK equ $fffd
SELECT_ROM_BANK equ $2000
OBP0 equ $ff48
OBP1 equ $ff49
BUTTON_A equ $01
BUTTON_B equ $02
BUTTON_SELECT equ $04
BUTTON_START equ $08
BUTTON_RIGHT equ $10
BUTTON_LEFT equ $20
BUTTON_UP equ $40
BUTTON_DOWN equ $80
CUR_WORLD_AND_LEVEL equ $ffb4
CUR_LEVEL equ $ffe4
CUR_CHECKPOINT equ $ffe5
TILE_BLANK equ $2c
TILE_ARROWS_ACTIVE equ $30
TILE_ARROWS_INACTIVE equ $31
TILE_FIREFLOWER equ $32
TILE_VERSION_1 equ $33
TILE_VERSION_2 equ $34
TILE_MUSHROOM equ $ac
TILE_DASH equ $29
MENU_Y equ $78
NUM_GRAPHICS equ 5
JOYPAD0 equ $ff80
JOYPAD1 equ $ff81
MY_ROM_BANK equ 4
CUR_BIGNESS equ $ff99
FIREFLOWER_FLAG equ $ffb5
rLCDC equ $ff40
rLY equ $ff44
rNR50 equ $ff24
rNR51 equ $ff25
rNR52 equ $ff26
LINE_VBLANK equ $90
NUM_LIVES equ $da15
FIRST_RUN_MAGIC equ $ca
SPRITE_BUFFER equ $c000
HARD_MODE_FLAG equ $ff9a
HARD_MODE_Y_COORD equ $84
SPRITE_SLOT_SELECTIONS equ $c000
SPRITE_SLOT_ARROWS equ $c010
SPRITE_SLOT_VERSION equ $c020
SPRITE_SLOT_HARD equ $c028
DELAY_FRAMES equ 60
SECTION "overwrite_before_deletion", ROM0[$01be]
jp jump_preserve_variables
SECTION "overwrite_title_screen", ROM0[$02c4]
dw jump_title_screen
SECTION "overwrite_game_start", ROM0[$02c8]
dw jump_game_start
SECTION "overwrite_boot", ROM0[$0425]
call jump_boot
SECTION "overwrite_demo", ROM0[$0519]
ret
; no demo makes room for own code
SECTION "read_joypad", ROM0[$051a]
read_joypad:
ld a, 3
ld [CUR_ROM_BANK], a
ld [SELECT_ROM_BANK], a
call $47f2
ld a, MY_ROM_BANK
ld [CUR_ROM_BANK], a
ld [SELECT_ROM_BANK], a
ret
my_level_music_start_before:
ld a, [CUR_ROM_BANK]
ld [LAST_ROM_BANK], a
ld a, 3
ld [CUR_ROM_BANK], a
ld [SELECT_ROM_BANK], a
ret
IF VERSION == 10
SECTION "overwrite_lives", ROM0[$3d3f]
ELSE
SECTION "overwrite_lives", ROM0[$3d48]
ENDC
ld a, $20
; fix starman crash
IF VERSION == 10
SECTION "overwrite_level_music_start_before", ROM0[$0791]
ELSE
SECTION "overwrite_level_music_start_before", ROM0[$07a8]
ENDC
call my_level_music_start_before
nop
nop
IF VERSION == 10
SECTION "overwrite_level_music_start_after", ROM0[$0799]
ELSE
SECTION "overwrite_level_music_start_after", ROM0[$07b0]
ENDC
call my_level_music_start_after
nop
nop
IF VERSION == 10
SECTION "level_music_after", ROM0[$00f1]
ELSE
SECTION "level_music_after", ROM0[$001b]
ENDC
my_level_music_start_after:
ld a, [LAST_ROM_BANK]
ld [CUR_ROM_BANK], a
ld [SELECT_ROM_BANK], a
ret
IF VERSION == 10
SECTION "overwrite_checkpoint", ROM0[$0dca]
ELSE
SECTION "overwrite_checkpoint", ROM0[$0dca+9]
ENDC
di
ld a, MY_ROM_BANK
ld [SELECT_ROM_BANK], a
call checkpoint_overwrite
ld a, [LAST_ROM_BANK]
ld [SELECT_ROM_BANK], a
ei
nop
nop
nop
nop
nop
nop
SECTION "jump1", ROM0[$3fce]
jump_game_start:
di
ld a, MY_ROM_BANK
ld [SELECT_ROM_BANK], a
call game_start
ld a, 2
ld [SELECT_ROM_BANK], a
IF VERSION == 10
jp $055f
ELSE
jp $0576
ENDC
jump_boot:
di
ld a, MY_ROM_BANK
ld [SELECT_ROM_BANK], a
call boot
ei
ret
jump_title_screen:
di
ld a, MY_ROM_BANK
ld [SELECT_ROM_BANK], a
call title_screen
ei
; replace original instructions
jp $04c3
jump_preserve_variables:
di
ld a, MY_ROM_BANK
ld [SELECT_ROM_BANK], a
jp preserve_variables
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
SECTION "code", ROMX[$4800], BANK[MY_ROM_BANK]
boot:
ld a, $00
ld [OBP1], a
call init_variables
call copy_graphics
call remove_start_text
call write_own_text
call draw_version
call init_arrows
call init_selections
call init_hard_mode_sprites
call draw_hard_mode
call draw_selections
call draw_arrows
; replace original instructions
xor a
ldh [$ff0f], a
ret
init_variables:
ld a, [FIRST_RUN]
cp FIRST_RUN_MAGIC
ret z
ld a, FIRST_RUN_MAGIC
ld [FIRST_RUN], a
ld a, 1
ld [SELECTED_WORLD], a
ld [SELECTED_LEVEL], a
ld [SELECTED_CHECKPOINT], a
ld [FIRST_LEVEL], a
xor a
ld [HARD_MODE_ON], a
ld [SELECTED_POWERUP], a
ld [CALCULATED_LEVEL], a
ld [CUR_SELECTION], a
ld a, $11
ld [CALCULATED_WORLD_AND_LEVEL], a
ld a, 3
ld [CALCULATED_CHECKPOINT], a
ld [CALCULATED_MAX_CHECKPOINTS], a
ret
draw_version:
xor a
ld [SPRITE_SLOT_VERSION+3], a
ld [SPRITE_SLOT_VERSION+7], a
ld a, 144 + 8
ld [SPRITE_SLOT_VERSION+0], a
ld a, 160 - 8
ld [SPRITE_SLOT_VERSION+1], a
ld a, TILE_VERSION_1
ld [SPRITE_SLOT_VERSION+2], a
ld a, 144 + 8
ld [SPRITE_SLOT_VERSION+4], a
ld a, 160 - 0
ld [SPRITE_SLOT_VERSION+5], a
ld a, TILE_VERSION_2
ld [SPRITE_SLOT_VERSION+6], a
ret
write_own_text:
ld a, "W" - "A" + 10
ld [$99a1], a
ld a, "L" - "A" + 10
ld [$99a6], a
ld a, "P" - "A" + 10
ld [$99ab], a
ld a, "C" - "A" + 10
ld [$99b0], a
ret
init_arrows:
; Y
ld a, MENU_Y
ld [SPRITE_SLOT_ARROWS+0], a
ld [SPRITE_SLOT_ARROWS+4], a
ld [SPRITE_SLOT_ARROWS+8], a
ld [SPRITE_SLOT_ARROWS+12], a
; WORLD ARROWS
ld a, $18
ld [SPRITE_SLOT_ARROWS+1], a
; LEVEL ARROWS
ld a, $40
ld [SPRITE_SLOT_ARROWS+5], a
; POWERUP ARROWS
ld a, $68
ld [SPRITE_SLOT_ARROWS+9], a
; CHECKPOINT ARROWS
ld a, $90
ld [SPRITE_SLOT_ARROWS+13], a
ret
draw_arrows:
ld a, TILE_ARROWS_INACTIVE
ld [SPRITE_SLOT_ARROWS+2], a
ld [SPRITE_SLOT_ARROWS+6], a
ld [SPRITE_SLOT_ARROWS+10], a
ld [SPRITE_SLOT_ARROWS+14], a
ld a, [CUR_SELECTION]
sla a
sla a
ld hl, SPRITE_SLOT_ARROWS+2
ld d, 0
ld e, a
add hl, de
ld [hl], TILE_ARROWS_ACTIVE
ret
init_selections:
; Y
ld a, MENU_Y
ld [SPRITE_SLOT_SELECTIONS+0], a
ld [SPRITE_SLOT_SELECTIONS+4], a
ld [SPRITE_SLOT_SELECTIONS+8], a
ld [SPRITE_SLOT_SELECTIONS+12], a
; 0X
ld a, $20
ld [SPRITE_SLOT_SELECTIONS+1], a
; 1X
ld a, $48
ld [SPRITE_SLOT_SELECTIONS+5], a
; 2X
ld a, $70
ld [SPRITE_SLOT_SELECTIONS+9], a
; 3X
ld a, $98
ld [SPRITE_SLOT_SELECTIONS+13], a
ret
draw_selections:
ld a, [SELECTED_WORLD]
ld [SPRITE_SLOT_SELECTIONS+2], a
ld a, [SELECTED_LEVEL]
ld [SPRITE_SLOT_SELECTIONS+6], a
ld a, [SELECTED_POWERUP]
ld hl, tile_table
ld d, 0
ld e, a
add hl, de
ld a, [hl]
ld [SPRITE_SLOT_SELECTIONS+10], a
ld a, [SELECTED_CHECKPOINT]
ld [SPRITE_SLOT_SELECTIONS+14], a
ret
remove_start_text:
ld hl, $99a6
ld a, TILE_BLANK
ld b, 5
.loop
ld [hl+], a
dec b
jr nz, .loop
ret
copy_graphics:
ld hl, graphics
ld b, NUM_GRAPHICS*16
ld de, $8300
.loop
ld a, [hl+]
ld [de], a
inc de
dec b
jr nz, .loop
ret
title_screen:
call check_joypad
call recalculate
call draw_selections
call draw_arrows
call draw_hard_mode
ret
recalculate:
.recalculate_world_and_level
ld a, [SELECTED_LEVEL]
ld b, a
ld a, [SELECTED_WORLD]
sla a
sla a
sla a
sla a
or b
ld [CALCULATED_WORLD_AND_LEVEL], a
.recalculate_level:
ld a, [SELECTED_WORLD]
ld b, a
ld a, -3
.loop
add 3
dec b
jr nz, .loop
ld b, a
ld a, [SELECTED_LEVEL]
add b
dec a
ld [CALCULATED_LEVEL], a
.recalculate_checkpoint
ld a, [SELECTED_CHECKPOINT]
ld b, $03
dec a
jr z, .set_checkpoint
ld b, $08
dec a
jr z, .set_checkpoint
ld b, $0c
dec a
jr z, .set_checkpoint
ld b, $10
dec a
jr z, .set_checkpoint
ld b, $14
dec a
jr z, .set_checkpoint
ld b, $18
.set_checkpoint
ld a, b
ld [CALCULATED_CHECKPOINT], a
.recalculate_max_checkpoints
ld a, [SELECTED_LEVEL]
dec a
ld b, a
ld a, [SELECTED_WORLD]
dec a
sla a
sla a
or b
ld hl, checkpoint_table
ld d, 0
ld e, a
add hl, de
ld a, [hl]
ld [CALCULATED_MAX_CHECKPOINTS], a
ret
action_down:
.check_world
ld a, [CUR_SELECTION]
ld b, a
cp 0
jr nz, .check_level
.have_world
ld a, 1
ld [SELECTED_CHECKPOINT], a
ld a, [SELECTED_WORLD]
cp 1
jr nz, .world_normal
.world_back_down
ld a, 4
jr .world_cont
.world_normal
dec a
.world_cont
ld [SELECTED_WORLD], a
.check_level
ld a, b
cp 1
jr nz, .check_powerup
.have_level
ld a, 1
ld [SELECTED_CHECKPOINT], a
ld a, [SELECTED_LEVEL]
cp 1
jr nz, .level_normal
.level_back_down
ld a, 3
jr .level_cont
.level_normal
dec a
.level_cont
ld [SELECTED_LEVEL], a
.check_powerup
ld a, b
cp 2
jr nz, .check_checkpoint
.have_powerup
ld a, [SELECTED_POWERUP]
cp 0
jr nz, .powerup_normal
.powerup_back_down
ld a, 2
jr .powerup_cont
.powerup_normal
dec a
.powerup_cont
ld [SELECTED_POWERUP], a
.check_checkpoint
ld a, b
cp 3
ret nz
.have_checkpoint
ld a, [SELECTED_CHECKPOINT]
cp 1
jr nz, .checkpoint_normal
.checkpoint_back_down
ld a, [CALCULATED_MAX_CHECKPOINTS]
jr .checkpoint_cont
.checkpoint_normal
dec a
.checkpoint_cont
ld [SELECTED_CHECKPOINT], a
ret
action_up:
.check_world
ld a, [CUR_SELECTION]
ld b, a
cp 0
jr nz, .check_level
.have_world
ld a, 1
ld [SELECTED_CHECKPOINT], a
ld a, [SELECTED_WORLD]
cp 4
jr nz, .world_normal
.world_back_up
ld a, 1
jr .world_cont
.world_normal
inc a
.world_cont
ld [SELECTED_WORLD], a
.check_level
ld a, b
cp 1
jr nz, .check_powerup
.have_level
ld a, 1
ld [SELECTED_CHECKPOINT], a
ld a, [SELECTED_LEVEL]
cp 3
jr nz, .level_normal
.level_back_up
ld a, 1
jr .level_cont
.level_normal
inc a
.level_cont
ld [SELECTED_LEVEL], a
.check_powerup
ld a, b
cp 2
jr nz, .check_checkpoint
.have_powerup
ld a, [SELECTED_POWERUP]
cp 2
jr nz, .powerup_normal
.powerup_back_up
xor a
jr .powerup_cont
.powerup_normal
inc a
.powerup_cont
ld [SELECTED_POWERUP], a
.check_checkpoint
ld a, b
cp 3
ret nz
.have_checkpoint
ld a, [SELECTED_CHECKPOINT]
ld hl, CALCULATED_MAX_CHECKPOINTS
cp [hl]
jr nz, .checkpoint_normal
.checkpoint_back_up
ld a, 1
jr .checkpoint_cont
.checkpoint_normal
inc a
.checkpoint_cont
ld [SELECTED_CHECKPOINT], a
ret
action_right:
ld a, [CUR_SELECTION]
cp 3
jr nz, .right_normal
.right_back_left
xor a
jr .right_cont
.right_normal:
inc a
.right_cont
ld [CUR_SELECTION], a
ret
action_left:
ld a, [CUR_SELECTION]
cp 0
jr nz, .left_normal
.left_back_right
ld a, 3
jr .left_cont
.left_normal:
dec a
.left_cont
ld [CUR_SELECTION], a
ret
check_joypad:
ld a, [JOYPAD0]
ld c, a
ld a, [JOYPAD1]
and c
ld c, a
ld a, c
cp BUTTON_DOWN
call z, action_down
ld a, c
cp BUTTON_UP
call z, action_up
ld a, c
cp BUTTON_RIGHT
call z, action_right
ld a, c
cp BUTTON_LEFT
call z, action_left
ld a, c
cp BUTTON_SELECT
call z, toggle_hard_mode
ret
init_hard_mode_sprites:
xor a
ld [SPRITE_SLOT_HARD+3], a
ld [SPRITE_SLOT_HARD+7], a
ld [SPRITE_SLOT_HARD+11], a
ld [SPRITE_SLOT_HARD+15], a
ld a, $a0
ld [SPRITE_SLOT_HARD+0], a
ld [SPRITE_SLOT_HARD+4], a
ld [SPRITE_SLOT_HARD+8], a
ld [SPRITE_SLOT_HARD+12], a
ld a, 72 + 8*0
ld [SPRITE_SLOT_HARD+1], a
ld a, "H" - "A" + 10
ld [SPRITE_SLOT_HARD+2], a
ld a, 72 + 8*1
ld [SPRITE_SLOT_HARD+5], a
ld a, "A" - "A" + 10
ld [SPRITE_SLOT_HARD+6], a
ld a, 72 + 8*2
ld [SPRITE_SLOT_HARD+9], a
ld a, "R" - "A" + 10
ld [SPRITE_SLOT_HARD+10], a
ld a, 72 + 8*3
ld [SPRITE_SLOT_HARD+13], a
ld a, "D" - "A" + 10
ld [SPRITE_SLOT_HARD+14], a
ret
draw_hard_mode:
ld a, [HARD_MODE_ON]
and a
jr nz, .hard_mode_on
.hard_mode_off
ld a, $a0
jr .cont
.hard_mode_on
ld a, HARD_MODE_Y_COORD
.cont
ld [SPRITE_SLOT_HARD+0], a
ld [SPRITE_SLOT_HARD+4], a
ld [SPRITE_SLOT_HARD+8], a
ld [SPRITE_SLOT_HARD+12], a
ret
toggle_hard_mode:
ld a, [HARD_MODE_ON]
xor 1
ld [HARD_MODE_ON], a
ret
wait_vblank:
ld a, [rLY]
cp LINE_VBLANK+2
ret nc
jp wait_vblank
wait_new_frame:
ld a, [rLY]
cp LINE_VBLANK
ret c
jp wait_new_frame
start_delay:
di
call wait_vblank
ld a, [rLCDC]
and $fc
ld [rLCDC], a
ld a, DELAY_FRAMES
ld b, a
.loop
push bc
IF VERSION == 10
ld a, 1
ld [$ff12], a
ld [$ff17], a
ld [$ff21], a
xor a
ld [$ff10], a
ld [$ff1a], a
ELSE
ld a, $ff
ld [$ff25], a
ld a, $08
ld [$ff12], a
ld [$ff17], a
ld [$ff21], a
ld a, $80
ld [$ff14], a
ld [$ff19], a
ld [$ff23], a
xor a
ld [$ff10], a
ld [$ff1a], a
ENDC
call read_joypad
call wait_vblank
call wait_new_frame
pop bc
dec b
jr nz, .loop
.end
call wait_vblank
ld a, [rLCDC]
or $03
ld [rLCDC], a
ret
game_start:
ld a, $54
ld [OBP1], a
call start_delay
ld a, [CALCULATED_WORLD_AND_LEVEL]
ld [CUR_WORLD_AND_LEVEL], a
ld a, [CALCULATED_LEVEL]
ld [CUR_LEVEL], a
ld a, [HARD_MODE_ON]
ld [HARD_MODE_FLAG], a
ld a, 1
ld [FIRST_LEVEL], a
ld a, [SELECTED_POWERUP]
ld b, a
.check_small
cp 0
jr nz, .check_mushroom
.have_small
xor a
ld [CUR_BIGNESS], a
ld [FIREFLOWER_FLAG], a
ret
.check_mushroom
ld a, b
cp 1
jr nz, .check_fireflower
.have_mushroom
ld a, 2
ld [CUR_BIGNESS], a
xor a
ld [FIREFLOWER_FLAG], a
ret
.check_fireflower
ld a, b
cp 2
ret nz
.have_fireflower
ld a, 2
ld [CUR_BIGNESS], a
ld [FIREFLOWER_FLAG], a
ret
preserve_variables:
.save_variables
ld hl, variables
ld de, $9800
ld b, end_of_variables-variables
.save_variables_loop
ld a, [hl+]
ld [de], a
inc de
dec b
jr nz, .save_variables_loop
.clear_memory
xor a
ld hl, $dfff
ld c, $40
ld b, 0
.clear_memory_loop
ld [hl-], a
dec b
jr nz, .clear_memory_loop
dec c
jr nz, .clear_memory_loop
.restore_variables
ld hl, $9800
ld de, variables
ld b, end_of_variables-variables
.restore_variables_loop
ld a, [hl+]
ld [de], a
inc de
dec b
jr nz, .restore_variables_loop
jp $01cc
checkpoint_overwrite:
; replace original instructions
xor a
ld [$ff0f], a
ld a, $c3
ld [$ff40], a
ld a, [FIRST_LEVEL]
dec a
ld a, 3
jr nz, .cont
.overwrite
xor a
ld [FIRST_LEVEL], a
ld a, [CALCULATED_CHECKPOINT]
.cont
ld [CUR_CHECKPOINT], a
; replace original instructions
xor a
ld [$c0d2], a
ld [$fff9], a
ld a, 2
ld [$ffb3], a
ret
graphics:
incbin "gfx/out/up_down_arrows_active.2bpp"
incbin "gfx/out/up_down_arrows_inactive.2bpp"
incbin "gfx/fireflower.2bpp"
incbin "gfx/out/version.2bpp"
tile_table:
db TILE_DASH, TILE_MUSHROOM, TILE_FIREFLOWER
checkpoint_table:
db 4, 4, 4, 0
db 4, 4, 5, 0
db 6, 4, 4, 0
db 6, 5, 6, 0
SECTION "variables", WRAM0[$cb00]
variables:
CUR_SELECTION: db
SELECTED_WORLD: db
SELECTED_LEVEL: db
SELECTED_POWERUP: db
SELECTED_CHECKPOINT: db
CALCULATED_WORLD_AND_LEVEL: db
CALCULATED_LEVEL: db
CALCULATED_CHECKPOINT: db
CALCULATED_MAX_CHECKPOINTS: db
FIRST_RUN: db
FIRST_LEVEL: db
HARD_MODE_ON: db
LAST_ROM_BANK: db
TEMP: db
end_of_variables:
|
; A002057: Fourth convolution of Catalan numbers: 4*binomial(2n+3,n)/(n+4).
; 1,4,14,48,165,572,2002,7072,25194,90440,326876,1188640,4345965,15967980,58929450,218349120,811985790,3029594040,11338026180,42550029600,160094486370,603784920024,2282138106804,8643460269248,32798844771700,124680849918352,474746313150648,1810502068789568,6914663035042301,26444792798594380,101268000658146714,388271781325244544,1490397410607839734,5727227396045850968,22031207552900835380,84832254137763216672,326957646155962397590,1261276298816540508040,4869664507084913916380
add $0,2
mov $1,$0
mov $2,$0
mul $0,2
sub $2,2
bin $0,$2
mul $0,2
div $0,$1
|
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include <random>
#include <vector>
#include "gtest/gtest.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/framework/program_desc.h"
#include "paddle/fluid/framework/tensor_util.h"
#include "paddle/fluid/operators/fused/cudnn_norm_conv.cu.h"
#include "paddle/fluid/operators/math/math_function.h"
#include "paddle/fluid/platform/float16.h"
namespace framework = paddle::framework;
namespace platform = paddle::platform;
namespace op = paddle::operators;
using Tensor = paddle::framework::Tensor;
USE_OP(conv2d);
USE_OP(conv2d_grad);
USE_OP_DEVICE_KERNEL(conv2d, CUDNN);
USE_OP_DEVICE_KERNEL(conv2d_grad, CUDNN);
template <typename T>
void InitRandomTensor(const std::vector<int64_t> &dims,
framework::Tensor *cpu_out) {
T *cpu_out_ptr = cpu_out->mutable_data<T>(framework::make_ddim(dims),
platform::CPUPlace());
std::default_random_engine random(0);
std::uniform_real_distribution<float> dis(0.0, 1.0);
for (int i = 0; i < cpu_out->numel(); ++i) {
cpu_out_ptr[i] = static_cast<T>(dis(random));
}
}
template <typename T>
void TransposeNchwToNhwc(const framework::Tensor &cpu_in,
framework::Tensor *cpu_out) {
auto in_dims = cpu_in.dims();
EXPECT_EQ(cpu_in.dims().size(), 4);
const T *cpu_in_ptr = cpu_in.data<T>();
T *cpu_out_ptr = cpu_out->mutable_data<T>(
{in_dims[0], in_dims[2], in_dims[3], in_dims[1]}, platform::CPUPlace());
int64_t n = in_dims[0];
int64_t c = in_dims[1];
int64_t hw = in_dims[2] * in_dims[3];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < hw; ++j) {
for (int k = 0; k < c; ++k) {
int dst_idx = i * hw * c + j * c + k;
int src_idx = i * c * hw + k * hw + j;
cpu_out_ptr[dst_idx] = cpu_in_ptr[src_idx];
}
}
}
}
template <typename T>
void CheckOutput(const framework::Tensor &cpu_res,
const framework::Tensor &cpu_base, float diff,
bool is_relative_atol = false) {
EXPECT_EQ(cpu_res.dims(), cpu_base.dims());
const T *cpu_res_ptr = cpu_res.data<T>();
const T *cpu_base_ptr = cpu_base.data<T>();
for (int i = 0; i < cpu_res.numel(); ++i) {
if (is_relative_atol) {
EXPECT_LT(static_cast<float>(std::abs((cpu_res_ptr[i] - cpu_base_ptr[i]) /
cpu_base_ptr[i])),
diff);
} else {
EXPECT_LT(static_cast<float>(std::abs(cpu_res_ptr[i] - cpu_base_ptr[i])),
diff);
}
}
}
// Use Paddle conv2d op results as baseline
template <typename T>
void ComputeConv2DForward(const platform::CUDADeviceContext &ctx,
const Tensor &cpu_input, const Tensor &cpu_filter,
Tensor *cpu_output) {
framework::Scope scope;
auto *input = scope.Var("Input")->GetMutable<framework::LoDTensor>();
auto *filter = scope.Var("Filter")->GetMutable<framework::LoDTensor>();
auto *output = scope.Var("Output")->GetMutable<framework::LoDTensor>();
auto place = ctx.GetPlace();
TensorCopySync(cpu_input, place, input);
TensorCopySync(cpu_filter, place, filter);
framework::AttributeMap attrs;
bool use_cudnn = true;
std::string data_format = "NHWC";
std::string padding_algorithm = "SAME";
attrs.insert({"use_cudnn", use_cudnn});
attrs.insert({"data_format", data_format});
attrs.insert({"padding_algorithm", padding_algorithm});
auto op = framework::OpRegistry::CreateOp(
"conv2d", {{"Input", {"Input"}}, {"Filter", {"Filter"}}},
{{"Output", {"Output"}}}, attrs);
op->Run(scope, ctx.GetPlace());
TensorCopySync(*output, platform::CPUPlace(), cpu_output);
}
// Use Paddle conv2d_grad op results as baseline
template <typename T>
void ComputeConv2DBackward(const platform::CUDADeviceContext &ctx,
const Tensor &cpu_input, const Tensor &cpu_filter,
const Tensor &cpu_output_grad,
framework::Tensor *cpu_input_grad,
framework::Tensor *cpu_filter_grad, int stride,
int padding, int dilation) {
framework::Scope scope;
auto *input = scope.Var("Input")->GetMutable<framework::LoDTensor>();
auto *filter = scope.Var("Filter")->GetMutable<framework::LoDTensor>();
auto *output_grad =
scope.Var("Output@GRAD")->GetMutable<framework::LoDTensor>();
auto *input_grad =
scope.Var("Input@GRAD")->GetMutable<framework::LoDTensor>();
auto *filter_grad =
scope.Var("Filter@GRAD")->GetMutable<framework::LoDTensor>();
auto place = ctx.GetPlace();
TensorCopySync(cpu_input, place, input);
TensorCopySync(cpu_filter, place, filter);
TensorCopySync(cpu_output_grad, place, output_grad);
framework::AttributeMap attrs;
bool use_cudnn = true;
std::string data_format = "NHWC";
std::string padding_algorithm = "SAME";
std::vector<int> strides = {stride, stride};
std::vector<int> paddings = {padding, padding};
std::vector<int> dilations = {dilation, dilation};
int groups = 1;
bool exhaustive_search = false;
bool use_addto = false;
attrs.insert({"use_cudnn", use_cudnn});
attrs.insert({"data_format", data_format});
attrs.insert({"padding_algorithm", padding_algorithm});
attrs.insert({"strides", strides});
attrs.insert({"paddings", paddings});
attrs.insert({"dilations", dilations});
attrs.insert({"groups", groups});
attrs.insert({"exhaustive_search", exhaustive_search});
attrs.insert({"use_addto", use_addto});
auto op = framework::OpRegistry::CreateOp(
"conv2d_grad", {{"Input", {"Input"}},
{"Filter", {"Filter"}},
{"Output@GRAD", {"Output@GRAD"}}},
{{"Input@GRAD", {"Input@GRAD"}}, {"Filter@GRAD", {"Filter@GRAD"}}},
attrs);
op->Run(scope, ctx.GetPlace());
TensorCopySync(*input_grad, platform::CPUPlace(), cpu_input_grad);
TensorCopySync(*filter_grad, platform::CPUPlace(), cpu_filter_grad);
}
template <typename T>
void ComputeSumAndSquareSum(const framework::Tensor &cpu_out,
framework::Tensor *cpu_sum,
framework::Tensor *cpu_sum_of_square) {
auto dims = cpu_out.dims();
int64_t c = dims[3];
const T *cpu_out_ptr = cpu_out.data<T>();
float *cpu_sum_ptr =
cpu_sum->mutable_data<float>({1, 1, 1, c}, platform::CPUPlace());
float *cpu_sum_square_ptr = cpu_sum_of_square->mutable_data<float>(
{1, 1, 1, c}, platform::CPUPlace());
for (int j = 0; j < c; ++j) {
float tmp_sum = 0.0f;
float tmp_sum_of_squares = 0.0f;
for (int i = 0; i < cpu_out.numel() / c; ++i) {
float tmp_out = static_cast<float>(cpu_out_ptr[i * c + j]);
tmp_sum += tmp_out;
tmp_sum_of_squares += tmp_out * tmp_out;
}
cpu_sum_ptr[j] = tmp_sum;
cpu_sum_square_ptr[j] = tmp_sum_of_squares;
}
}
template <typename T>
class CudnnNormConvolutionTester {
public:
CudnnNormConvolutionTester(int batch_size, int height, int width,
int input_channels, int output_channels,
int kernel_size, int stride) {
batch_size_ = batch_size;
height_ = height;
width_ = width;
input_channels_ = input_channels;
output_channels_ = output_channels;
kernel_size_ = kernel_size;
stride_ = stride;
padding_ = (kernel_size_ - 1) / 2;
SetUp();
}
~CudnnNormConvolutionTester() {}
void CheckForward(float diff, bool is_relative_atol = false) {
platform::CUDADeviceContext *ctx =
static_cast<platform::CUDADeviceContext *>(
platform::DeviceContextPool::Instance().Get(
platform::CUDAPlace(0)));
framework::Tensor cpu_output_base;
framework::Tensor cpu_sum_base;
framework::Tensor cpu_sum_of_square_base;
BaselineForward(*ctx, &cpu_output_base, &cpu_sum_base,
&cpu_sum_of_square_base);
framework::Tensor cpu_output;
framework::Tensor cpu_sum;
framework::Tensor cpu_sum_of_square;
FusedForward(*ctx, &cpu_output, &cpu_sum, &cpu_sum_of_square);
// Check forward correctness between baseline and results of normconv.
CheckOutput<T>(cpu_output, cpu_output_base, diff, is_relative_atol);
CheckOutput<float>(cpu_sum, cpu_sum_base, diff, is_relative_atol);
CheckOutput<float>(cpu_sum_of_square, cpu_sum_of_square_base, diff,
is_relative_atol);
}
void CheckBackward(float diff, bool is_relative_atol = false) {
platform::CUDADeviceContext *ctx =
static_cast<platform::CUDADeviceContext *>(
platform::DeviceContextPool::Instance().Get(
platform::CUDAPlace(0)));
framework::Tensor cpu_input_grad_base;
framework::Tensor cpu_filter_nchw_grad_base;
framework::Tensor cpu_filter_nhwc_grad_base;
BaselineBackward(*ctx, &cpu_input_grad_base, &cpu_filter_nchw_grad_base);
TransposeNchwToNhwc<T>(cpu_filter_nchw_grad_base,
&cpu_filter_nhwc_grad_base);
framework::Tensor cpu_input_grad;
framework::Tensor cpu_filter_nhwc_grad;
FusedBackward(*ctx, &cpu_input_grad, &cpu_filter_nhwc_grad);
// Check backward correctness between baseline and results of normconv.
CheckOutput<T>(cpu_input_grad, cpu_input_grad_base, diff, is_relative_atol);
CheckOutput<T>(cpu_filter_nhwc_grad, cpu_filter_nhwc_grad_base, diff,
is_relative_atol);
}
private:
void SetUp() {
InitRandomTensor<T>({batch_size_, height_, width_, input_channels_},
&cpu_input_);
InitRandomTensor<T>(
{output_channels_, input_channels_, kernel_size_, kernel_size_},
&cpu_filter_nchw_);
// transpoes for filter, NCHW -> NHWC
TransposeNchwToNhwc<T>(cpu_filter_nchw_, &cpu_filter_nhwc_);
InitRandomTensor<T>({batch_size_, height_, width_, output_channels_},
&cpu_output_grad_);
}
void BaselineForward(const platform::CUDADeviceContext &ctx,
framework::Tensor *cpu_output_base,
framework::Tensor *cpu_sum_base,
framework::Tensor *cpu_sum_of_square_base) {
ComputeConv2DForward<T>(ctx, cpu_input_, cpu_filter_nchw_, cpu_output_base);
ComputeSumAndSquareSum<T>(*cpu_output_base, cpu_sum_base,
cpu_sum_of_square_base);
}
void BaselineBackward(const platform::CUDADeviceContext &ctx,
framework::Tensor *cpu_input_grad_base,
framework::Tensor *cpu_filter_grad_base) {
ComputeConv2DBackward<T>(ctx, cpu_input_, cpu_filter_nchw_,
cpu_output_grad_, cpu_input_grad_base,
cpu_filter_grad_base, stride_, padding_,
dilation_);
}
// get forward results of cudnn_norm_conv
void FusedForward(const platform::CUDADeviceContext &ctx,
framework::Tensor *cpu_output, framework::Tensor *cpu_sum,
framework::Tensor *cpu_sum_of_square) {
framework::Tensor input;
framework::Tensor filter_nhwc;
framework::Tensor output;
framework::Tensor sum;
framework::Tensor sum_of_square;
auto place = ctx.GetPlace();
TensorCopySync(cpu_input_, place, &input);
TensorCopySync(cpu_filter_nhwc_, place, &filter_nhwc);
T *input_ptr = input.data<T>();
T *filter_ptr = filter_nhwc.data<T>();
T *output_ptr = output.mutable_data<T>(
{batch_size_, height_, width_, output_channels_}, place);
float *sum_ptr =
sum.mutable_data<float>({1, 1, 1, output_channels_}, place);
float *sum_of_square_ptr =
sum_of_square.mutable_data<float>({1, 1, 1, output_channels_}, place);
auto input_shape = framework::vectorize<int>(input.dims());
auto filter_shape = framework::vectorize<int>(filter_nhwc.dims());
auto output_shape = framework::vectorize<int>(output.dims());
op::CudnnNormConvolution<T> conv_op(ctx, input_shape, filter_shape,
output_shape, padding_, stride_,
dilation_, group_);
conv_op.Forward(ctx, input_ptr, filter_ptr, output_ptr, sum_ptr,
sum_of_square_ptr);
TensorCopySync(output, platform::CPUPlace(), cpu_output);
TensorCopySync(sum, platform::CPUPlace(), cpu_sum);
TensorCopySync(sum_of_square, platform::CPUPlace(), cpu_sum_of_square);
}
void FusedBackward(const platform::CUDADeviceContext &ctx,
framework::Tensor *cpu_input_grad,
framework::Tensor *cpu_filter_grad) {
framework::Tensor input;
framework::Tensor filter_nhwc;
framework::Tensor output_grad;
framework::Tensor input_grad;
framework::Tensor filter_grad;
auto place = ctx.GetPlace();
TensorCopySync(cpu_input_, place, &input);
TensorCopySync(cpu_filter_nhwc_, place, &filter_nhwc);
TensorCopySync(cpu_output_grad_, place, &output_grad);
T *input_ptr = input.data<T>();
T *filter_ptr = filter_nhwc.data<T>();
T *output_grad_ptr = output_grad.data<T>();
T *input_grad_ptr = input_grad.mutable_data<T>(input.dims(), place);
T *filter_grad_ptr = filter_grad.mutable_data<T>(filter_nhwc.dims(), place);
auto input_shape = framework::vectorize<int>(input.dims());
auto filter_shape = framework::vectorize<int>(filter_nhwc.dims());
auto output_shape = framework::vectorize<int>(output_grad.dims());
op::CudnnNormConvolutionGrad<T> conv_grad_op(ctx, input_shape, filter_shape,
output_shape, padding_,
stride_, dilation_, group_);
conv_grad_op.Backward(ctx, input_ptr, output_grad_ptr, filter_ptr,
input_grad_ptr, filter_grad_ptr);
TensorCopySync(input_grad, platform::CPUPlace(), cpu_input_grad);
TensorCopySync(filter_grad, platform::CPUPlace(), cpu_filter_grad);
}
private:
int batch_size_;
int height_;
int width_;
int input_channels_;
int output_channels_;
int kernel_size_;
int stride_;
int padding_;
const int dilation_ = 1;
const int group_ = 1;
// Forward input
framework::Tensor cpu_input_;
framework::Tensor cpu_filter_nchw_;
framework::Tensor cpu_filter_nhwc_;
// Backward input
framework::Tensor cpu_output_grad_;
};
// test for fp16, kernel = 1, output_channels = input_channels
TEST(CudnnNormConvFp16, K1S1) {
int batch_size = 4;
int height = 56;
int width = 56;
int input_channels = 32;
int output_channels = 32;
int kernel_size = 1;
int stride = 1;
CudnnNormConvolutionTester<paddle::platform::float16> test(
batch_size, height, width, input_channels, output_channels, kernel_size,
stride);
test.CheckForward(1e-3, true);
test.CheckBackward(1e-3, true);
}
// test for fp16, kernel = 3, output_channels = input_channels
TEST(CudnnNormConvFp16, K3S1) {
int batch_size = 4;
int height = 56;
int width = 56;
int input_channels = 32;
int output_channels = 32;
int kernel_size = 3;
int stride = 1;
CudnnNormConvolutionTester<paddle::platform::float16> test(
batch_size, height, width, input_channels, output_channels, kernel_size,
stride);
test.CheckForward(1e-3, true);
test.CheckBackward(1e-3, true);
}
// test for fp16, kernel = 1, output_channels = input_channels * 4
TEST(CudnnNormConvFp16, K1S1O4) {
int batch_size = 4;
int height = 56;
int width = 56;
int input_channels = 32;
int output_channels = 128;
int kernel_size = 1;
int stride = 1;
CudnnNormConvolutionTester<paddle::platform::float16> test(
batch_size, height, width, input_channels, output_channels, kernel_size,
stride);
test.CheckForward(1e-3, true);
test.CheckBackward(1e-3, true);
}
|
// Copyright 2014 Ryuichi Ueda
// Released under the MIT License.
#include "ExeEachline.h"
//#include "ArgCommand.h"
//#include "InternalCommands.h"
#include "Environment.h"
#include "Script.h"
#include "Arg.h"
#include "Where.h"
#include "DefFile.h"
#include "DefStr.h"
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include "Feeder.h"
#include "ExeProc.h"
#include "ExeString.h"
#include "ExeExtCom.h"
#include "ExeIntCom.h"
using namespace std;
ExeEachline::ExeEachline(Feeder *f, Environment *env) : Exe(f,env)
{
}
ExeEachline::~ExeEachline()
{
}
bool ExeEachline::parse(void)
{
m_feeder->getPos(&m_start_line, &m_start_char);
if(!m_feeder->str("eachline")){
return false;
}
bool res = add(new ExeProc(m_feeder,m_env))
|| add(new ExeIntCom(m_feeder,m_env))
|| add(new ExeExtCom(m_feeder,m_env));
if(!res){
m_feeder->setPos(m_start_line, m_start_char);
return false;
}
m_feeder->getPos(&m_end_line, &m_end_char);
return true;
}
void ExeEachline::execChild(void)
{
auto *com = (Exe *)m_nodes[0];
string line;
while (getline(cin, line)){
//vector<string> ws;
line += ' ';//add a space at the end of a line
int from = 0;
for(int i=from;i<line.size();i++){
if(line.at(i) == ' '){
com->appendArg(line.substr(from,i-from));
from = i + 1;
}
}
int pid = com->exec();
com->clearAppendArg();
waitCommands(pid);
if(m_exit_status != 0)
exit(m_exit_status);
}
exit(0);
}
//copy from PipeLine.cc (It's not cool.)
void ExeEachline::waitCommands(int pid)
{
int options = 0;
int status;
int wpid = waitpid(pid,&status,options);
if(wpid < 1){
m_error_msg = "Command wait error";
m_exit_status = 2;
throw this;
}
if(!WIFEXITED(status)){
if(WIFSIGNALED(status) && WTERMSIG(status) == 13){//ignore sigpipe
// The exit status of the command that is suffered a sigpipe
// should be zero because the command itself does not anything bad.
m_exit_status = 0;
}else{
m_error_msg = "Irregular command termination";
m_exit_status = 2;
throw this;
}
}else{
m_exit_status = WEXITSTATUS(status);
}
if(m_env->m_v_opt)
cerr << "+ pid " << pid << " exit " << m_exit_status << endl;
if(m_exit_status == 0)
return;
m_error_msg = "Command error";
throw this;
}
|
; A010013: a(0) = 1, a(n) = 23*n^2 + 2 for n>0.
; 1,25,94,209,370,577,830,1129,1474,1865,2302,2785,3314,3889,4510,5177,5890,6649,7454,8305,9202,10145,11134,12169,13250,14377,15550,16769,18034,19345,20702,22105,23554,25049,26590,28177,29810,31489,33214,34985,36802,38665,40574,42529,44530,46577,48670,50809,52994,55225,57502,59825,62194,64609,67070,69577,72130,74729,77374,80065,82802,85585,88414,91289,94210,97177,100190,103249,106354,109505,112702,115945,119234,122569,125950,129377,132850,136369,139934,143545,147202,150905,154654,158449,162290,166177,170110,174089,178114,182185,186302,190465,194674,198929,203230,207577,211970,216409,220894,225425,230002,234625,239294,244009,248770,253577,258430,263329,268274,273265,278302,283385,288514,293689,298910,304177,309490,314849,320254,325705,331202,336745,342334,347969,353650,359377,365150,370969,376834,382745,388702,394705,400754,406849,412990,419177,425410,431689,438014,444385,450802,457265,463774,470329,476930,483577,490270,497009,503794,510625,517502,524425,531394,538409,545470,552577,559730,566929,574174,581465,588802,596185,603614,611089,618610,626177,633790,641449,649154,656905,664702,672545,680434,688369,696350,704377,712450,720569,728734,736945,745202,753505,761854,770249,778690,787177,795710,804289,812914,821585,830302,839065,847874,856729,865630,874577,883570,892609,901694,910825,920002,929225,938494,947809,957170,966577,976030,985529,995074,1004665,1014302,1023985,1033714,1043489,1053310,1063177,1073090,1083049,1093054,1103105,1113202,1123345,1133534,1143769,1154050,1164377,1174750,1185169,1195634,1206145,1216702,1227305,1237954,1248649,1259390,1270177,1281010,1291889,1302814,1313785,1324802,1335865,1346974,1358129,1369330,1380577,1391870,1403209,1414594,1426025
pow $1,$0
gcd $1,2
mov $3,$0
mul $3,$0
mov $2,$3
mul $2,23
add $1,$2
|
;;
;; Copyright (c) 2012-2018, Intel Corporation
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;;
;; * Redistributions of source code must retain the above copyright notice,
;; this list of conditions and the following disclaimer.
;; * 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.
;; * Neither the name of Intel Corporation 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 OWNER 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.
;;
;; Stack must be aligned to 32 bytes before call
;;
;; Registers: RAX RBX RCX RDX RBP RSI RDI R8 R9 R10 R11 R12 R13 R14 R15
;; -----------------------------------------------------------
;; Windows clobbers: RDX R10 R11
;; Windows preserves: RAX RBX RCX RBP RSI RDI R8 R9 R12 R13 R14 R15
;; -----------------------------------------------------------
;; Linux clobbers: RDI R10 R11
;; Linux preserves: RAX RBX RCX RDX RBP RSI R8 R9 R12 R13 R14 R15
;; -----------------------------------------------------------
;;
;; Linux/Windows clobbers: xmm0 - xmm15
%include "include/os.asm"
;%define DO_DBGPRINT
%include "include/dbgprint.asm"
%include "mb_mgr_datastruct.asm"
%ifdef LINUX
%define arg1 rdi
%define arg2 rsi
%define arg3 rcx
%define arg4 rdx
%else
%define arg1 rcx
%define arg2 rdx
%define arg3 rdi
%define arg4 rsi
%endif
%define args arg1
%define NUM_BLKS arg2
; reso = resdq => 16 bytes
struc frame
.ABCD_SAVE reso 1
.E_SAVE reso 1
.ABCD_SAVEb reso 1
.E_SAVEb reso 1
.align resq 1
endstruc
%define INP r10
%define INPb r11
%define ABCD xmm0
%define E0 xmm1 ; Need two E's b/c they ping pong
%define E1 xmm2
%define MSG0 xmm3
%define MSG1 xmm4
%define MSG2 xmm5
%define MSG3 xmm6
%define ABCDb xmm7
%define E0b xmm8 ; Need two E's b/c they ping pong
%define E1b xmm9
%define MSG0b xmm10
%define MSG1b xmm11
%define MSG2b xmm12
%define MSG3b xmm13
%define SHUF_MASK xmm14
%define E_MASK xmm15
section .data
default rel
align 64
PSHUFFLE_BYTE_FLIP_MASK: ;ddq 0x000102030405060708090a0b0c0d0e0f
dq 0x08090a0b0c0d0e0f, 0x0001020304050607
UPPER_WORD_MASK: ;ddq 0xFFFFFFFF000000000000000000000000
dq 0x0000000000000000, 0xFFFFFFFF00000000
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; void sha1_ni(SHA1_ARGS *args, UINT32 size_in_blocks)
;; arg1 : pointer to args
;; arg2 : size (in blocks) ;; assumed to be >= 1
section .text
MKGLOBAL(sha1_ni,function,internal)
align 32
sha1_ni:
sub rsp, frame_size
DBGPRINTL "enter sha1-ni-x2"
shl NUM_BLKS, 6 ; convert to bytes
jz done_hash
;; load input pointers
mov INP, [args + _data_ptr_sha1 + 0*PTR_SZ]
DBGPRINTL64 "jobA: pointer", INP
mov INPb, [args + _data_ptr_sha1 + 1*PTR_SZ]
add NUM_BLKS, INP ; pointer to end of data block -> loop exit condition
;; load initial digest
movdqu ABCD, [args + 0*SHA1NI_DIGEST_ROW_SIZE]
pxor E0, E0
pinsrd E0, [args + 0*SHA1NI_DIGEST_ROW_SIZE + 4*SHA1_DIGEST_WORD_SIZE], 3
pshufd ABCD, ABCD, 0x1B
DBGPRINTL_XMM "jobA: digest in words[0-3]", ABCD
DBGPRINTL_XMM "jobA: digest in word 4", E0
movdqu ABCDb, [args + 1*SHA1NI_DIGEST_ROW_SIZE]
pxor E0b, E0b
pinsrd E0b, [args + 1*SHA1NI_DIGEST_ROW_SIZE + 4*SHA1_DIGEST_WORD_SIZE], 3
pshufd ABCDb, ABCDb, 0x1B
movdqa SHUF_MASK, [rel PSHUFFLE_BYTE_FLIP_MASK]
movdqa E_MASK, [rel UPPER_WORD_MASK]
DBGPRINTL "jobA data:"
loop0:
;; Copy digests
movdqa [rsp + frame.ABCD_SAVE], ABCD
movdqa [rsp + frame.E_SAVE], E0
movdqa [rsp + frame.ABCD_SAVEb], ABCDb
movdqa [rsp + frame.E_SAVEb], E0b
;; Only needed if not using sha1nexte for rounds 0-3
pand E0, E_MASK
pand E0b, E_MASK
;; Needed if using sha1nexte for rounds 0-3
;; Need to rotate E right by 30
;movdqa E1, E0
;psrld E0, 30
;pslld E1, 2
;pxor E0, E1
;; Rounds 0-3
movdqu MSG0, [INP + 0*16]
pshufb MSG0, SHUF_MASK
DBGPRINT_XMM MSG0
;sha1nexte E0, MSG0
paddd E0, MSG0 ; instead of sha1nexte
movdqa E1, ABCD
sha1rnds4 ABCD, E0, 0
movdqu MSG0b, [INPb + 0*16]
pshufb MSG0b, SHUF_MASK
;sha1nexte E0b, MSG0b
paddd E0b, MSG0b ; instead of sha1nexte
movdqa E1b, ABCDb
sha1rnds4 ABCDb, E0b, 0
;; Rounds 4-7
movdqu MSG1, [INP + 1*16]
pshufb MSG1, SHUF_MASK
DBGPRINT_XMM MSG1
sha1nexte E1, MSG1
movdqa E0, ABCD
sha1rnds4 ABCD, E1, 0
sha1msg1 MSG0, MSG1
movdqu MSG1b, [INPb + 1*16]
pshufb MSG1b, SHUF_MASK
sha1nexte E1b, MSG1b
movdqa E0b, ABCDb
sha1rnds4 ABCDb, E1b, 0
sha1msg1 MSG0b, MSG1b
;; Rounds 8-11
movdqu MSG2, [INP + 2*16]
pshufb MSG2, SHUF_MASK
DBGPRINT_XMM MSG2
sha1nexte E0, MSG2
movdqa E1, ABCD
sha1rnds4 ABCD, E0, 0
sha1msg1 MSG1, MSG2
pxor MSG0, MSG2
movdqu MSG2b, [INPb + 2*16]
pshufb MSG2b, SHUF_MASK
sha1nexte E0b, MSG2b
movdqa E1b, ABCDb
sha1rnds4 ABCDb, E0b, 0
sha1msg1 MSG1b, MSG2b
pxor MSG0b, MSG2b
;; Rounds 12-15
movdqu MSG3, [INP + 3*16]
pshufb MSG3, SHUF_MASK
DBGPRINT_XMM MSG3
sha1nexte E1, MSG3
movdqa E0, ABCD
sha1msg2 MSG0, MSG3
sha1rnds4 ABCD, E1, 0
sha1msg1 MSG2, MSG3
pxor MSG1, MSG3
movdqu MSG3b, [INPb + 3*16]
pshufb MSG3b, SHUF_MASK
sha1nexte E1b, MSG3b
movdqa E0b, ABCDb
sha1msg2 MSG0b, MSG3b
sha1rnds4 ABCDb, E1b, 0
sha1msg1 MSG2b, MSG3b
pxor MSG1b, MSG3b
;; Rounds 16-19
sha1nexte E0, MSG0
movdqa E1, ABCD
sha1msg2 MSG1, MSG0
sha1rnds4 ABCD, E0, 0
sha1msg1 MSG3, MSG0
pxor MSG2, MSG0
sha1nexte E0b, MSG0b
movdqa E1b, ABCDb
sha1msg2 MSG1b, MSG0b
sha1rnds4 ABCDb, E0b, 0
sha1msg1 MSG3b, MSG0b
pxor MSG2b, MSG0b
;; Rounds 20-23
sha1nexte E1, MSG1
movdqa E0, ABCD
sha1msg2 MSG2, MSG1
sha1rnds4 ABCD, E1, 1
sha1msg1 MSG0, MSG1
pxor MSG3, MSG1
sha1nexte E1b, MSG1b
movdqa E0b, ABCDb
sha1msg2 MSG2b, MSG1b
sha1rnds4 ABCDb, E1b, 1
sha1msg1 MSG0b, MSG1b
pxor MSG3b, MSG1b
;; Rounds 24-27
sha1nexte E0, MSG2
movdqa E1, ABCD
sha1msg2 MSG3, MSG2
sha1rnds4 ABCD, E0, 1
sha1msg1 MSG1, MSG2
pxor MSG0, MSG2
sha1nexte E0b, MSG2b
movdqa E1b, ABCDb
sha1msg2 MSG3b, MSG2b
sha1rnds4 ABCDb, E0b, 1
sha1msg1 MSG1b, MSG2b
pxor MSG0b, MSG2b
;; Rounds 28-31
sha1nexte E1, MSG3
movdqa E0, ABCD
sha1msg2 MSG0, MSG3
sha1rnds4 ABCD, E1, 1
sha1msg1 MSG2, MSG3
pxor MSG1, MSG3
sha1nexte E1b, MSG3b
movdqa E0b, ABCDb
sha1msg2 MSG0b, MSG3b
sha1rnds4 ABCDb, E1b, 1
sha1msg1 MSG2b, MSG3b
pxor MSG1b, MSG3b
;; Rounds 32-35
sha1nexte E0, MSG0
movdqa E1, ABCD
sha1msg2 MSG1, MSG0
sha1rnds4 ABCD, E0, 1
sha1msg1 MSG3, MSG0
pxor MSG2, MSG0
sha1nexte E0b, MSG0b
movdqa E1b, ABCDb
sha1msg2 MSG1b, MSG0b
sha1rnds4 ABCDb, E0b, 1
sha1msg1 MSG3b, MSG0b
pxor MSG2b, MSG0b
;; Rounds 36-39
sha1nexte E1, MSG1
movdqa E0, ABCD
sha1msg2 MSG2, MSG1
sha1rnds4 ABCD, E1, 1
sha1msg1 MSG0, MSG1
pxor MSG3, MSG1
sha1nexte E1b, MSG1b
movdqa E0b, ABCDb
sha1msg2 MSG2b, MSG1b
sha1rnds4 ABCDb, E1b, 1
sha1msg1 MSG0b, MSG1b
pxor MSG3b, MSG1b
;; Rounds 40-43
sha1nexte E0, MSG2
movdqa E1, ABCD
sha1msg2 MSG3, MSG2
sha1rnds4 ABCD, E0, 2
sha1msg1 MSG1, MSG2
pxor MSG0, MSG2
sha1nexte E0b, MSG2b
movdqa E1b, ABCDb
sha1msg2 MSG3b, MSG2b
sha1rnds4 ABCDb, E0b, 2
sha1msg1 MSG1b, MSG2b
pxor MSG0b, MSG2b
;; Rounds 44-47
sha1nexte E1, MSG3
movdqa E0, ABCD
sha1msg2 MSG0, MSG3
sha1rnds4 ABCD, E1, 2
sha1msg1 MSG2, MSG3
pxor MSG1, MSG3
sha1nexte E1b, MSG3b
movdqa E0b, ABCDb
sha1msg2 MSG0b, MSG3b
sha1rnds4 ABCDb, E1b, 2
sha1msg1 MSG2b, MSG3b
pxor MSG1b, MSG3b
;; Rounds 48-51
sha1nexte E0, MSG0
movdqa E1, ABCD
sha1msg2 MSG1, MSG0
sha1rnds4 ABCD, E0, 2
sha1msg1 MSG3, MSG0
pxor MSG2, MSG0
sha1nexte E0b, MSG0b
movdqa E1b, ABCDb
sha1msg2 MSG1b, MSG0b
sha1rnds4 ABCDb, E0b, 2
sha1msg1 MSG3b, MSG0b
pxor MSG2b, MSG0b
;; Rounds 52-55
sha1nexte E1, MSG1
movdqa E0, ABCD
sha1msg2 MSG2, MSG1
sha1rnds4 ABCD, E1, 2
sha1msg1 MSG0, MSG1
pxor MSG3, MSG1
sha1nexte E1b, MSG1b
movdqa E0b, ABCDb
sha1msg2 MSG2b, MSG1b
sha1rnds4 ABCDb, E1b, 2
sha1msg1 MSG0b, MSG1b
pxor MSG3b, MSG1b
;; Rounds 56-59
sha1nexte E0, MSG2
movdqa E1, ABCD
sha1msg2 MSG3, MSG2
sha1rnds4 ABCD, E0, 2
sha1msg1 MSG1, MSG2
pxor MSG0, MSG2
sha1nexte E0b, MSG2b
movdqa E1b, ABCDb
sha1msg2 MSG3b, MSG2b
sha1rnds4 ABCDb, E0b, 2
sha1msg1 MSG1b, MSG2b
pxor MSG0b, MSG2b
;; Rounds 60-63
sha1nexte E1, MSG3
movdqa E0, ABCD
sha1msg2 MSG0, MSG3
sha1rnds4 ABCD, E1, 3
sha1msg1 MSG2, MSG3
pxor MSG1, MSG3
sha1nexte E1b, MSG3b
movdqa E0b, ABCDb
sha1msg2 MSG0b, MSG3b
sha1rnds4 ABCDb, E1b, 3
sha1msg1 MSG2b, MSG3b
pxor MSG1b, MSG3b
;; Rounds 64-67
sha1nexte E0, MSG0
movdqa E1, ABCD
sha1msg2 MSG1, MSG0
sha1rnds4 ABCD, E0, 3
sha1msg1 MSG3, MSG0
pxor MSG2, MSG0
sha1nexte E0b, MSG0b
movdqa E1b, ABCDb
sha1msg2 MSG1b, MSG0b
sha1rnds4 ABCDb, E0b, 3
sha1msg1 MSG3b, MSG0b
pxor MSG2b, MSG0b
;; Rounds 68-71
sha1nexte E1, MSG1
movdqa E0, ABCD
sha1msg2 MSG2, MSG1
sha1rnds4 ABCD, E1, 3
pxor MSG3, MSG1
sha1nexte E1b, MSG1b
movdqa E0b, ABCDb
sha1msg2 MSG2b, MSG1b
sha1rnds4 ABCDb, E1b, 3
pxor MSG3b, MSG1b
;; Rounds 72-75
sha1nexte E0, MSG2
movdqa E1, ABCD
sha1msg2 MSG3, MSG2
sha1rnds4 ABCD, E0, 3
sha1nexte E0b, MSG2b
movdqa E1b, ABCDb
sha1msg2 MSG3b, MSG2b
sha1rnds4 ABCDb, E0b, 3
;; Rounds 76-79
sha1nexte E1, MSG3
movdqa E0, ABCD
sha1rnds4 ABCD, E1, 3
sha1nexte E1b, MSG3b
movdqa E0b, ABCDb
sha1rnds4 ABCDb, E1b, 3
;; Need to rotate E left by 30
movdqa E1, E0
pslld E0, 30
psrld E1, 2
pxor E0, E1
movdqa E1b, E0b
pslld E0b, 30
psrld E1b, 2
pxor E0b, E1b
paddd ABCD, [rsp + frame.ABCD_SAVE]
paddd E0, [rsp + frame.E_SAVE]
paddd ABCDb, [rsp + frame.ABCD_SAVEb]
paddd E0b, [rsp + frame.E_SAVEb]
add INP, 64
add INPb, 64
cmp INP, NUM_BLKS
jne loop0
;; write out digests
pshufd ABCD, ABCD, 0x1B
movdqu [args + 0*SHA1NI_DIGEST_ROW_SIZE], ABCD
pextrd [args + 0*SHA1NI_DIGEST_ROW_SIZE + 4*SHA1_DIGEST_WORD_SIZE], E0, 3
DBGPRINTL_XMM "jobA: digest out words[0-3]", ABCD
DBGPRINTL_XMM "jobA: digest out word 4", E0
pshufd ABCDb, ABCDb, 0x1B
movdqu [args + 1*SHA1NI_DIGEST_ROW_SIZE], ABCDb
pextrd [args + 1*SHA1NI_DIGEST_ROW_SIZE + 4*SHA1_DIGEST_WORD_SIZE], E0b, 3
;; update input pointers
mov [args + _data_ptr_sha1 + 0*PTR_SZ], INP
mov [args + _data_ptr_sha1 + 1*PTR_SZ], INPb
done_hash:
add rsp, frame_size
ret
%ifdef LINUX
section .note.GNU-stack noalloc noexec nowrite progbits
%endif
|
#include <arrow/api.h>
#include <arrow/ipc/api.h>
#include <arrow/io/api.h>
#include <fletcher/api.h>
#include <fletcher/common.h>
#include <malloc.h>
#include <unistd.h>
#include <memory>
#include <iostream>
#include <bitset>
#define AFU_GUID "5fcd29a3-1c65-4feb-907f-34c5ba4c8534";
#ifdef NDEBUG
#define PLATFORM "opae"
#else
#define PLATFORM "opae-ase"
//#define PLATFORM "echo"
#endif
arrow::Result<std::shared_ptr<arrow::PrimitiveArray>> AlignedPrimitiveArray(const std::shared_ptr<arrow::DataType>& type,
size_t buffer_size) {
uint8_t *value_data = (uint8_t *)memalign(sysconf(_SC_PAGESIZE), buffer_size);
if (value_data == nullptr)
{
return arrow::Status::OutOfMemory("Failed to allocate buffer");
}
auto value_buffer = std::make_shared<arrow::Buffer>(value_data, buffer_size);
auto value_array = std::make_shared<arrow::PrimitiveArray>(type, 0, value_buffer);
return value_array;
}
arrow::Result<std::shared_ptr<arrow::ListArray>> AlignedListArray(const std::shared_ptr<arrow::DataType>& type,
size_t offset_buffer_size,
size_t value_buffer_size) {
uint8_t *offset_data = (uint8_t *)memalign(sysconf(_SC_PAGESIZE), offset_buffer_size);
if (offset_data == nullptr)
{
return arrow::Status::OutOfMemory("Failed to allocate offset buffer");
}
memset(offset_data, 0, offset_buffer_size);
auto offset_buffer = std::make_shared<arrow::Buffer>(offset_data, offset_buffer_size);
uint8_t *value_data = (uint8_t *)memalign(sysconf(_SC_PAGESIZE), value_buffer_size);
if (value_data == nullptr)
{
return arrow::Status::OutOfMemory("Failed to allocate value buffer");
}
auto value_buffer = std::make_shared<arrow::Buffer>(value_data, value_buffer_size);
auto value_array = std::make_shared<arrow::PrimitiveArray>(arrow::uint64(), 0, value_buffer);
auto list_array = std::make_shared<arrow::ListArray>(arrow::list(arrow::uint64()), 0, offset_buffer, value_array);
return arrow::ToResult(list_array);
}
arrow::Result<std::shared_ptr<arrow::StringArray>> AlignedStringArray(size_t offset_buffer_size,
size_t value_buffer_size) {
uint8_t *offset_data = (uint8_t *)memalign(sysconf(_SC_PAGESIZE), offset_buffer_size);
if (offset_data == nullptr)
{
return arrow::Status::OutOfMemory("Failed to allocate buffer");
}
memset(offset_data, 0, offset_buffer_size);
auto offset_buffer = std::make_shared<arrow::Buffer>(offset_data, offset_buffer_size);
uint8_t *value_data = (uint8_t *)memalign(sysconf(_SC_PAGESIZE), value_buffer_size);
if (value_data == nullptr)
{
return arrow::Status::OutOfMemory("Failed to allocate buffer");
}
auto value_buffer = std::make_shared<arrow::Buffer>(value_data, value_buffer_size);
auto string_array = std::make_shared<arrow::StringArray>(0, offset_buffer, value_buffer);
return arrow::ToResult(string_array);
}
std::shared_ptr<arrow::PrimitiveArray>ReWrapArray(std::shared_ptr<arrow::PrimitiveArray> array,
size_t num_rows) {
auto data_buff = array->data()->buffers[1]->data();
auto value_buffer = std::make_shared<arrow::Buffer>(data_buff, num_rows);
auto value_array = std::make_shared<arrow::PrimitiveArray>(arrow::uint64(), num_rows, value_buffer);
return value_array;
}
std::shared_ptr<arrow::ListArray>ReWrapArray(std::shared_ptr<arrow::ListArray> array,
size_t num_rows) {
auto type = array->type();
int32_t num_offsets = num_rows + 1;
uint8_t *offsets = (uint8_t *)array->offsets()->data()->buffers[1]->data();
uint8_t *values = const_cast<uint8_t *>(array->values()->data()->buffers[1]->data());
uint32_t num_values = reinterpret_cast<uint32_t *>(offsets)[num_offsets-1];
size_t num_values_bytes = num_values * sizeof(array->type().get());
size_t num_offset_bytes = num_offsets * sizeof(uint32_t);
auto value_buffer = arrow::Buffer::Wrap(values, num_values_bytes);
auto offsets_buffer = arrow::Buffer::Wrap(offsets, num_offset_bytes);
auto value_array = std::make_shared<arrow::PrimitiveArray>(arrow::uint64(), num_values, value_buffer);
auto list_array = std::make_shared<arrow::ListArray>(type, num_rows, offsets_buffer, value_array);
return list_array;
}
std::shared_ptr<arrow::StringArray>ReWrapArray(std::shared_ptr<arrow::StringArray> array,
size_t num_rows) {
auto string_array = std::make_shared<arrow::StringArray>(num_rows, array->value_offsets(), array->value_data());
return string_array;
}
arrow::Status WrapTripReport(
int32_t num_rows,
std::vector<std::shared_ptr<arrow::Array>> arrays,
std::shared_ptr<arrow::Schema> schema,
std::shared_ptr<arrow::RecordBatch> *out)
{
std::vector<std::shared_ptr<arrow::Array>> rewrapped_arrays;
for(std::shared_ptr<arrow::Array> f: arrays) {
std::cout << f->type()->ToString() << std::endl;
if(f->type()->Equals(arrow::uint64())) {
auto field = std::static_pointer_cast<arrow::PrimitiveArray>(f);
rewrapped_arrays.push_back(ReWrapArray(field, num_rows));
} else if(f->type()->Equals(arrow::uint8())) {
auto field = std::static_pointer_cast<arrow::PrimitiveArray>(f);
rewrapped_arrays.push_back(ReWrapArray(field, num_rows));
} else if (f->type()->Equals(arrow::list(arrow::uint64()))) {
auto field = std::static_pointer_cast<arrow::ListArray>(f);
rewrapped_arrays.push_back(ReWrapArray(field, num_rows));
} else if (f->type()->Equals(arrow::utf8())) {
auto field = std::static_pointer_cast<arrow::StringArray>(f);
rewrapped_arrays.push_back(ReWrapArray(field, num_rows));
}
}
*out = arrow::RecordBatch::Make(schema, num_rows, rewrapped_arrays);
return arrow::Status::OK();
}
int main(int argc, char **argv)
{
if (argc != 3)
{
std::cerr << "Incorrect number of arguments. Usage: trip_report path/to/input_recordbatch.rb path/to/output_recordbatch.rb" << std::endl;
return -1;
}
std::vector<std::shared_ptr<arrow::RecordBatch>> batches;
fletcher::ReadRecordBatchesFromFile(argv[1], &batches);
if (batches.size() != 1)
{
std::cerr << "File did not contain any input Arrow RecordBatches." << std::endl;
return -1;
}
std::shared_ptr<arrow::RecordBatch> input_batch;
input_batch = batches[0];
// read output schema
auto file = arrow::io::ReadableFile::Open(argv[2]).ValueOrDie();
std::shared_ptr<arrow::Schema> schema = arrow::ipc::ReadSchema(file.get(), nullptr)
.ValueOrDie();
file->Close();
size_t buffer_size = 4096;
std::vector<std::shared_ptr<arrow::Array>> arrays;
for(auto f : schema->fields()) {
if(f->type()->Equals(arrow::uint64())) {
arrays.push_back(AlignedPrimitiveArray(arrow::uint64(), buffer_size).ValueOrDie());
} else if(f->type()->Equals(arrow::uint8())) {
arrays.push_back(AlignedPrimitiveArray(arrow::uint8(), buffer_size).ValueOrDie());
} else if (f->type()->Equals(arrow::list(arrow::field("item", arrow::uint64(), false)))) {
arrays.push_back(AlignedListArray(arrow::uint64(), buffer_size, buffer_size).ValueOrDie());
} else if (f->type()->Equals(arrow::utf8())) {
arrays.push_back(AlignedStringArray(buffer_size, buffer_size).ValueOrDie());
}
}
auto output_batch = arrow::RecordBatch::Make(schema, 0, arrays);
fletcher::Status status;
std::shared_ptr<fletcher::Platform> platform;
status = fletcher::Platform::Make(PLATFORM, &platform, false);
if (!status.ok())
{
std::cerr << "Could not create Fletcher platform." << std::endl;
std::cerr << status.message << std::endl;
return -1;
}
static const char *guid = AFU_GUID;
platform->init_data = &guid;
status = platform->Init();
if (!status.ok())
{
std::cerr << "Could not initialize platform." << std::endl;
std::cerr << status.message << std::endl;
return -1;
}
std::shared_ptr<fletcher::Context> context;
status = fletcher::Context::Make(&context, platform);
if (!status.ok())
{
std::cerr << "Could not create Fletcher context." << std::endl;
return -1;
}
status = context->QueueRecordBatch(input_batch);
if (!status.ok())
{
std::cerr << "Could not add input recordbatch." << std::endl;
return -1;
}
status = context->QueueRecordBatch(output_batch);
if (!status.ok())
{
std::cerr << "Could not add output recordbatch." << std::endl;
return -1;
}
status = context->Enable();
if (!status.ok())
{
std::cerr << "Could not enable the context." << std::endl;
return -1;
}
for (int i = 0; i < context->num_buffers(); i++)
{
auto view = fletcher::HexView();
view.AddData(context->device_buffer(i).host_address, 64);
std::cout << view.ToString() << std::endl;
}
fletcher::Kernel kernel(context);
status = kernel.Start();
if (!status.ok())
{
std::cerr << "Could not start the kernel." << std::endl;
return -1;
}
status = kernel.PollUntilDone();
if (!status.ok())
{
std::cerr << "Something went wrong waiting for the kernel to finish." << std::endl;
return -1;
}
// uint32_t return_value_0;
// uint32_t return_value_1;
// uint64_t state = 0;
// uint64_t num_rows = 0;
// while(state != 96) {
// status = kernel.GetReturn(&return_value_0, &return_value_1);
// state = ((uint64_t)112) & ((uint64_t)return_value_0);
// num_rows = ((uint64_t)3) & ((uint64_t)return_value_0);
// uint64_t reg = ((uint64_t)return_value_1 << 32) | return_value_0;
// std::cout << "Result reg:" << std::hex << reg << std::endl;
// if (!status.ok())
// {
// std::cerr << "Failed to get return value." << std::endl;
// return -1;
// }
// usleep(1000000);
// }
uint32_t return_value_0;
uint32_t return_value_1;
status = kernel.GetReturn(&return_value_0, &return_value_1);
if (!status.ok())
{
std::cerr << "Failed to get return value." << std::endl;
return -1;
}
uint64_t num_rows = ((uint64_t)return_value_1 << 32) | return_value_0;
std::cout << "Number of records parsed: " << num_rows << std::endl;
auto arrow_status = WrapTripReport(num_rows, arrays, schema, &output_batch);
if (!arrow_status.ok())
{
std::cerr << "Could not create output recordbatch." << std::endl;
std::cerr << arrow_status.ToString() << std::endl;
return -1;
}
std::cout << output_batch->ToString() << std::endl;
return 0;
} |
sllv $5,$4,$3
subu $3,$3,$3
addiu $1,$5,17725
addu $5,$3,$3
sltiu $6,$1,-14985
slt $0,$0,$3
subu $4,$5,$3
lbu $5,7($0)
srav $1,$3,$3
ori $3,$3,13639
xori $4,$4,63889
lw $1,4($0)
srlv $4,$5,$3
addu $4,$5,$3
sh $1,16($0)
sw $6,12($0)
nor $4,$4,$3
sltu $5,$3,$3
srav $0,$4,$3
lbu $3,16($0)
sllv $3,$4,$3
lw $3,16($0)
slt $1,$3,$3
sra $4,$1,28
srlv $3,$1,$3
sltu $3,$4,$3
subu $3,$3,$3
lbu $1,9($0)
lhu $4,0($0)
sll $3,$3,0
xor $5,$5,$3
subu $5,$4,$3
srl $6,$4,31
lw $4,4($0)
sllv $3,$0,$3
sh $3,0($0)
sh $5,14($0)
subu $3,$3,$3
subu $3,$0,$3
sltu $6,$4,$3
srl $0,$0,16
xori $3,$3,26843
nor $4,$4,$3
sra $0,$1,21
xori $3,$3,17066
addiu $4,$3,16703
lw $5,12($0)
slti $6,$0,30840
sll $1,$4,13
addiu $5,$1,-12730
sll $3,$0,6
sb $4,13($0)
nor $1,$3,$3
lb $3,5($0)
ori $3,$3,62835
slt $1,$1,$3
ori $0,$0,54520
xor $3,$3,$3
addu $3,$1,$3
srav $4,$3,$3
lhu $3,14($0)
or $5,$6,$3
srlv $4,$4,$3
srlv $5,$3,$3
addu $1,$0,$3
xor $3,$3,$3
srl $4,$3,18
or $0,$3,$3
sh $4,10($0)
xor $4,$4,$3
lhu $4,4($0)
addiu $0,$0,14680
sb $3,7($0)
srlv $1,$3,$3
lb $5,0($0)
and $3,$1,$3
andi $3,$3,26399
lhu $5,2($0)
andi $1,$4,21672
lh $3,4($0)
sll $1,$3,21
addu $3,$3,$3
or $5,$6,$3
addiu $6,$1,13255
addu $1,$1,$3
sltiu $1,$2,7713
sltu $3,$6,$3
subu $3,$2,$3
addiu $3,$3,20597
sra $3,$3,12
srl $4,$6,31
xor $3,$5,$3
sllv $4,$5,$3
and $1,$6,$3
sw $3,16($0)
nor $1,$4,$3
lh $0,2($0)
addu $3,$3,$3
lw $0,12($0)
sllv $3,$2,$3
srav $5,$6,$3
or $3,$0,$3
xor $4,$4,$3
sh $6,14($0)
lhu $3,16($0)
sllv $5,$5,$3
slt $4,$4,$3
sb $5,2($0)
or $3,$1,$3
addu $3,$3,$3
srlv $1,$1,$3
srav $3,$0,$3
lhu $3,10($0)
andi $0,$3,58394
sw $1,16($0)
and $4,$1,$3
slti $3,$1,-4335
slti $1,$4,32206
srav $1,$0,$3
addiu $1,$6,19102
slti $2,$2,-522
lh $3,16($0)
andi $3,$6,35751
lhu $1,14($0)
addu $0,$4,$3
addiu $4,$4,28047
addu $5,$6,$3
sra $1,$5,29
slti $3,$1,6622
addu $4,$5,$3
sra $4,$4,4
sh $4,10($0)
srl $1,$1,23
slti $1,$3,-208
srav $5,$1,$3
srlv $3,$3,$3
srlv $4,$0,$3
addiu $3,$3,2415
lbu $3,1($0)
sh $6,12($0)
sllv $3,$3,$3
sll $4,$5,23
lw $4,8($0)
lh $3,10($0)
lb $6,7($0)
subu $3,$3,$3
slti $6,$3,28048
sll $5,$5,24
lb $6,8($0)
xor $5,$3,$3
and $2,$2,$3
lh $4,0($0)
or $6,$1,$3
sh $0,16($0)
srl $5,$6,1
xor $0,$3,$3
slti $3,$6,-10026
andi $6,$3,48456
lw $3,16($0)
slt $6,$6,$3
subu $0,$5,$3
srl $3,$5,30
xori $6,$3,17734
subu $3,$4,$3
lhu $3,2($0)
lh $3,6($0)
lw $4,8($0)
sh $3,10($0)
xor $5,$3,$3
or $5,$4,$3
lw $5,8($0)
lbu $3,9($0)
sllv $4,$1,$3
srlv $6,$6,$3
xori $4,$3,51186
sltiu $3,$1,19335
sltiu $1,$4,-28842
addu $5,$3,$3
addu $4,$4,$3
lhu $5,16($0)
nor $4,$1,$3
srlv $3,$1,$3
lh $0,16($0)
nor $1,$1,$3
nor $4,$4,$3
nor $4,$1,$3
and $3,$3,$3
srl $4,$1,19
srlv $0,$3,$3
addiu $3,$3,10383
and $4,$6,$3
srl $3,$6,8
addu $4,$2,$3
andi $3,$3,48020
lh $4,14($0)
lb $4,9($0)
lbu $1,0($0)
ori $4,$4,46103
lb $5,5($0)
addu $1,$3,$3
addu $3,$1,$3
sll $6,$4,13
sll $4,$4,29
slti $1,$3,-31031
addu $1,$4,$3
sll $3,$3,19
sllv $3,$4,$3
srl $1,$1,25
addiu $5,$3,-9521
subu $4,$4,$3
lb $3,10($0)
srlv $4,$4,$3
sltu $4,$4,$3
lb $3,13($0)
slti $1,$1,-18990
lh $0,14($0)
sll $1,$3,24
srlv $6,$6,$3
srav $3,$4,$3
lh $0,2($0)
lb $3,10($0)
or $5,$4,$3
lh $3,4($0)
addu $4,$4,$3
slti $5,$3,-23581
lbu $5,2($0)
srlv $6,$3,$3
sw $1,16($0)
slti $5,$4,4965
ori $3,$4,20566
addiu $1,$4,-15307
lbu $4,1($0)
sltu $3,$1,$3
sll $5,$4,19
xor $3,$3,$3
lh $3,2($0)
ori $0,$0,22566
sll $0,$5,29
addu $6,$1,$3
or $1,$1,$3
xori $4,$4,65492
sllv $1,$2,$3
sh $6,2($0)
sw $4,4($0)
slti $3,$3,3761
sra $4,$3,4
lh $5,12($0)
lhu $1,6($0)
srlv $4,$3,$3
andi $0,$2,60423
sll $3,$5,7
sll $1,$3,7
srl $4,$4,28
subu $0,$4,$3
nor $5,$5,$3
sra $4,$4,13
xor $5,$5,$3
lhu $4,6($0)
sb $5,7($0)
addiu $0,$3,-5831
subu $1,$3,$3
sw $4,4($0)
addu $4,$5,$3
sllv $3,$4,$3
lhu $3,16($0)
lbu $5,8($0)
srl $3,$4,28
sll $4,$4,4
or $3,$4,$3
and $3,$6,$3
addiu $6,$1,19578
sltu $3,$2,$3
sh $3,4($0)
xori $5,$4,5852
sh $3,14($0)
sllv $6,$5,$3
sh $6,2($0)
lw $5,0($0)
addiu $0,$5,20952
sll $4,$1,31
sltu $5,$5,$3
sll $1,$3,5
sll $4,$4,17
lb $3,0($0)
sra $4,$4,4
lw $0,4($0)
sb $4,0($0)
or $0,$3,$3
lw $4,4($0)
sb $3,10($0)
and $4,$3,$3
lb $4,11($0)
addiu $5,$5,30814
and $0,$0,$3
nor $3,$4,$3
and $3,$3,$3
subu $4,$4,$3
sltu $1,$4,$3
sra $5,$3,24
srlv $4,$3,$3
addu $4,$4,$3
nor $6,$4,$3
xor $3,$5,$3
sltu $5,$3,$3
srlv $5,$4,$3
sw $5,16($0)
sll $3,$5,5
sltu $4,$6,$3
lh $3,10($0)
addu $3,$3,$3
addiu $1,$5,-16177
sll $4,$6,21
and $4,$4,$3
subu $1,$1,$3
sb $0,14($0)
subu $4,$4,$3
ori $3,$6,5533
sw $0,4($0)
nor $1,$0,$3
subu $4,$0,$3
sra $4,$3,25
sw $4,4($0)
lh $3,2($0)
sb $1,10($0)
slt $0,$0,$3
sh $3,0($0)
ori $4,$4,3804
srlv $1,$4,$3
subu $0,$6,$3
andi $3,$3,45846
sh $4,4($0)
addiu $1,$3,20527
lw $3,0($0)
lw $1,16($0)
slt $3,$3,$3
slt $0,$0,$3
sw $5,16($0)
sra $3,$3,12
ori $4,$4,57300
sw $1,16($0)
lh $0,14($0)
andi $0,$4,29072
sltu $5,$3,$3
lb $3,14($0)
subu $1,$5,$3
sltiu $3,$3,-30747
sllv $3,$4,$3
xor $0,$5,$3
srl $5,$3,6
lh $1,6($0)
subu $6,$1,$3
and $3,$5,$3
lhu $3,2($0)
srav $5,$5,$3
sw $4,12($0)
lbu $1,0($0)
or $1,$3,$3
sra $0,$3,6
sra $3,$6,11
srav $1,$1,$3
sb $0,0($0)
addiu $3,$5,-31330
lw $1,16($0)
slt $4,$3,$3
and $4,$3,$3
sltiu $1,$3,17718
sb $5,14($0)
sb $5,1($0)
nor $3,$6,$3
sh $2,0($0)
sw $1,12($0)
addiu $1,$5,-17906
nor $3,$3,$3
subu $3,$3,$3
xori $6,$1,15523
lbu $3,5($0)
subu $6,$4,$3
srav $1,$3,$3
sw $3,16($0)
sh $4,2($0)
lw $3,4($0)
nor $3,$5,$3
sll $4,$4,1
lbu $2,10($0)
subu $5,$3,$3
addiu $1,$0,2495
addu $3,$3,$3
addu $4,$3,$3
ori $3,$6,38390
subu $3,$6,$3
andi $5,$1,54957
lb $0,9($0)
sltu $0,$0,$3
lbu $1,11($0)
subu $1,$6,$3
sllv $3,$4,$3
sltu $1,$1,$3
lh $5,4($0)
xor $4,$1,$3
lb $5,7($0)
lh $1,16($0)
srav $3,$4,$3
sltiu $3,$0,-6430
sb $5,13($0)
slt $0,$0,$3
sh $5,6($0)
lb $1,6($0)
lw $3,12($0)
addu $5,$1,$3
nor $4,$4,$3
lw $3,16($0)
sll $4,$4,9
srav $3,$3,$3
sll $6,$6,3
andi $4,$4,23673
srl $3,$5,23
nor $3,$3,$3
addiu $1,$0,1515
ori $4,$4,37012
lb $4,11($0)
slti $3,$3,15698
lhu $3,0($0)
xor $3,$0,$3
lb $5,7($0)
srl $4,$3,1
sltiu $3,$4,22989
sltiu $6,$2,-30743
lb $5,12($0)
slti $3,$5,-2812
sra $0,$1,28
or $4,$4,$3
addiu $3,$4,29856
lbu $1,10($0)
or $6,$4,$3
sw $3,0($0)
sltiu $5,$5,10261
srl $1,$4,4
and $4,$4,$3
srlv $6,$6,$3
xori $1,$1,18180
slt $6,$5,$3
sw $4,16($0)
andi $5,$3,31949
srlv $1,$3,$3
srl $3,$0,31
nor $4,$3,$3
lw $3,4($0)
nor $3,$3,$3
slt $3,$4,$3
slti $4,$5,15645
sb $4,5($0)
xor $1,$4,$3
sra $4,$4,29
srav $5,$5,$3
lb $4,15($0)
lbu $0,10($0)
lhu $3,4($0)
and $1,$3,$3
subu $1,$0,$3
srl $1,$1,12
slt $3,$3,$3
or $6,$4,$3
sltu $4,$5,$3
srl $5,$3,6
xor $0,$3,$3
sra $6,$5,11
lbu $3,5($0)
addu $4,$4,$3
addiu $0,$0,-13974
lbu $5,15($0)
addu $3,$3,$3
sltu $4,$3,$3
lb $3,2($0)
sltu $5,$5,$3
or $5,$1,$3
lw $5,16($0)
or $3,$5,$3
sltiu $4,$4,9519
srlv $5,$3,$3
lbu $4,4($0)
ori $3,$5,42295
sh $4,4($0)
addu $1,$4,$3
addu $4,$0,$3
lbu $3,6($0)
srl $3,$3,24
or $4,$4,$3
nor $1,$0,$3
sllv $6,$5,$3
lbu $1,15($0)
addiu $5,$0,-7161
subu $1,$1,$3
srlv $3,$3,$3
subu $3,$3,$3
lw $0,8($0)
addiu $4,$4,4277
slt $0,$0,$3
sltu $5,$4,$3
sra $3,$5,0
xor $4,$3,$3
srl $1,$5,9
xor $4,$4,$3
or $3,$0,$3
sb $3,3($0)
subu $1,$1,$3
and $5,$3,$3
sltu $1,$3,$3
sw $4,16($0)
subu $4,$6,$3
sllv $3,$1,$3
sh $5,6($0)
lh $3,8($0)
and $3,$3,$3
srlv $2,$2,$3
lw $6,12($0)
xor $1,$1,$3
lbu $0,11($0)
srav $5,$3,$3
nor $4,$2,$3
srav $3,$6,$3
sra $1,$3,21
sllv $0,$0,$3
sltiu $1,$1,-9521
addu $4,$4,$3
sltiu $5,$5,21466
subu $4,$4,$3
addiu $0,$3,5367
addiu $0,$0,23392
sltu $4,$5,$3
ori $3,$3,60937
slt $4,$3,$3
srl $3,$3,14
lhu $3,8($0)
nor $3,$3,$3
subu $5,$4,$3
slti $3,$3,19062
subu $6,$6,$3
or $4,$1,$3
slti $4,$4,-7700
sw $5,8($0)
lw $5,8($0)
addiu $4,$3,23859
sltiu $3,$3,16774
addu $0,$4,$3
srl $4,$5,24
sll $3,$4,18
and $4,$3,$3
addu $3,$3,$3
sltu $3,$4,$3
or $3,$1,$3
addiu $3,$5,-26160
sll $1,$3,5
sllv $3,$3,$3
sra $6,$5,30
lbu $5,9($0)
and $5,$0,$3
addu $1,$5,$3
and $3,$4,$3
lhu $3,16($0)
subu $5,$5,$3
addu $1,$6,$3
srlv $0,$4,$3
addiu $5,$0,-11370
sltiu $6,$3,5279
lbu $5,9($0)
addu $5,$5,$3
sll $3,$6,23
lbu $4,13($0)
xor $4,$5,$3
slti $6,$6,-13023
lb $5,9($0)
srlv $3,$3,$3
nor $1,$5,$3
srl $3,$3,15
srl $1,$4,2
srl $3,$1,6
sw $3,12($0)
sll $3,$3,11
sh $0,8($0)
srlv $5,$4,$3
lhu $5,4($0)
or $0,$0,$3
xor $6,$3,$3
nor $1,$3,$3
ori $3,$4,39379
srav $3,$1,$3
ori $5,$3,49285
lh $0,2($0)
sll $3,$5,17
or $4,$0,$3
lhu $6,14($0)
sw $4,16($0)
lbu $3,5($0)
sllv $3,$3,$3
addu $1,$1,$3
addu $0,$0,$3
lb $3,12($0)
xori $1,$6,10373
sltu $3,$3,$3
sh $0,10($0)
andi $4,$3,26415
lb $3,6($0)
subu $4,$6,$3
lbu $1,9($0)
sltu $1,$6,$3
xori $6,$0,29514
subu $1,$6,$3
sltu $6,$4,$3
sltu $5,$4,$3
srl $1,$3,31
lhu $3,6($0)
addiu $6,$6,18687
addiu $3,$3,6752
srav $3,$4,$3
subu $1,$1,$3
ori $0,$1,37588
addiu $3,$2,21600
subu $4,$5,$3
sltiu $5,$6,22692
lh $3,2($0)
sllv $5,$4,$3
sb $1,10($0)
lbu $3,16($0)
subu $5,$1,$3
lbu $4,5($0)
srav $3,$3,$3
addu $5,$5,$3
subu $4,$6,$3
sltu $4,$1,$3
ori $1,$3,43104
lhu $6,8($0)
nor $1,$3,$3
sltiu $4,$0,1266
sltu $3,$1,$3
srav $3,$0,$3
lb $3,3($0)
sh $1,10($0)
slti $1,$1,31126
sb $4,14($0)
slti $3,$4,-23411
subu $3,$1,$3
sb $3,16($0)
sb $4,15($0)
lb $4,6($0)
sb $5,1($0)
srav $5,$6,$3
addu $3,$3,$3
addu $5,$0,$3
xori $0,$0,54358
sra $4,$0,26
sltiu $0,$3,17801
subu $3,$4,$3
or $6,$3,$3
or $1,$1,$3
xori $3,$3,30689
addiu $6,$4,5006
xor $0,$0,$3
srav $1,$1,$3
xori $3,$3,52663
slti $0,$5,-20539
srl $4,$5,15
slti $4,$3,15255
sltu $3,$5,$3
sllv $5,$1,$3
andi $1,$1,28184
addiu $3,$3,-15573
lbu $1,3($0)
sll $5,$3,29
addiu $3,$5,-8033
lw $3,12($0)
lbu $6,13($0)
srlv $5,$5,$3
subu $4,$4,$3
sb $1,2($0)
addiu $5,$3,20000
andi $4,$4,61047
sllv $1,$3,$3
lbu $3,10($0)
srav $3,$5,$3
sllv $6,$5,$3
sw $4,4($0)
xor $3,$3,$3
sllv $4,$4,$3
xor $3,$3,$3
xor $5,$2,$3
addiu $3,$3,-9386
addu $3,$4,$3
lhu $4,6($0)
addiu $3,$1,-4775
subu $4,$4,$3
nor $1,$3,$3
srl $4,$3,21
xor $3,$3,$3
lb $5,5($0)
addu $4,$4,$3
nor $3,$3,$3
addiu $0,$3,2936
addu $5,$3,$3
xori $4,$0,39113
xor $4,$4,$3
sb $4,0($0)
sh $5,6($0)
or $4,$4,$3
sltu $3,$3,$3
sllv $3,$3,$3
addiu $3,$3,-30598
sll $4,$1,12
lb $5,10($0)
sra $4,$1,20
subu $0,$4,$3
sb $0,8($0)
srl $4,$4,23
sltiu $1,$3,29891
xori $3,$6,45038
sra $1,$5,27
addu $5,$3,$3
sllv $1,$1,$3
sh $6,10($0)
subu $5,$3,$3
andi $4,$5,16069
sll $6,$2,14
addu $3,$3,$3
lbu $3,0($0)
ori $3,$2,36636
and $1,$5,$3
xor $0,$1,$3
sllv $3,$4,$3
andi $6,$4,41606
sra $1,$4,16
sra $5,$3,23
sh $1,10($0)
xori $3,$0,7270
sh $3,14($0)
sltiu $3,$3,-6870
sh $0,16($0)
sll $6,$6,28
sh $5,8($0)
subu $1,$6,$3
sllv $5,$4,$3
addiu $0,$4,-15410
srav $4,$4,$3
sltu $6,$0,$3
subu $3,$2,$3
slti $4,$4,2025
sw $1,8($0)
xori $6,$3,48634
lbu $0,12($0)
addiu $1,$4,24954
and $4,$1,$3
lb $3,7($0)
ori $4,$0,62587
srl $5,$5,21
sra $0,$0,1
subu $5,$4,$3
sh $3,16($0)
subu $3,$3,$3
srlv $1,$0,$3
or $4,$4,$3
and $1,$3,$3
sltiu $4,$5,-26855
lh $3,4($0)
sltu $5,$5,$3
or $3,$5,$3
slt $6,$5,$3
ori $4,$4,18807
sllv $3,$3,$3
xor $5,$3,$3
xori $5,$1,15822
sllv $3,$6,$3
srl $3,$4,17
and $1,$3,$3
lw $2,12($0)
xori $6,$6,1487
lh $3,0($0)
xor $5,$3,$3
addiu $1,$3,-14522
lw $4,16($0)
and $5,$2,$3
or $1,$3,$3
andi $3,$1,56930
slti $5,$5,28413
ori $6,$0,7869
sw $4,16($0)
lb $1,11($0)
xori $6,$6,21826
sll $4,$1,14
lh $1,12($0)
sra $4,$4,25
sltu $5,$4,$3
sh $3,8($0)
addu $0,$5,$3
addiu $4,$4,16283
sltu $5,$1,$3
or $4,$1,$3
and $4,$6,$3
xori $0,$6,60612
lbu $0,16($0)
addu $3,$6,$3
addiu $0,$5,4645
subu $1,$1,$3
addu $5,$2,$3
addiu $3,$3,-18363
sll $4,$5,20
srav $5,$4,$3
lw $4,4($0)
slti $5,$5,-23476
lb $1,10($0)
addu $5,$5,$3
lh $3,10($0)
lhu $0,8($0)
sw $3,8($0)
lhu $1,4($0)
srav $5,$5,$3
subu $1,$4,$3
ori $1,$3,37401
lh $4,14($0)
sltiu $3,$3,-11710
lw $3,0($0)
or $4,$1,$3
sltiu $1,$1,30542
sll $0,$4,12
addiu $5,$4,8289
addiu $3,$3,-18997
lh $3,6($0)
subu $3,$5,$3
ori $3,$4,55605
lh $3,6($0)
sltu $3,$4,$3
addiu $4,$3,-6655
lw $6,8($0)
srlv $3,$3,$3
addiu $1,$4,1921
ori $3,$0,5779
lw $1,12($0)
lb $3,9($0)
andi $6,$5,48027
and $0,$6,$3
sltu $3,$3,$3
addu $1,$4,$3
sllv $5,$4,$3
lw $4,16($0)
lb $5,4($0)
addiu $3,$4,13029
ori $0,$3,54896
xor $1,$1,$3
slt $5,$0,$3
lb $5,5($0)
srav $4,$6,$3
addu $0,$5,$3
sra $6,$6,1
slti $1,$3,14662
lhu $4,0($0)
nor $0,$3,$3
addu $3,$3,$3
xori $6,$5,52307
lb $4,3($0)
srlv $1,$4,$3
lbu $3,2($0)
and $0,$5,$3
lhu $3,0($0)
sll $4,$4,1
srav $4,$0,$3
addiu $5,$3,19136
slt $6,$4,$3
lw $5,16($0)
slti $4,$4,16634
srlv $4,$3,$3
addiu $6,$3,-6200
and $3,$4,$3
sll $3,$0,21
srl $3,$3,25
sllv $0,$5,$3
andi $1,$4,27563
sltu $3,$1,$3
sh $5,4($0)
sltu $0,$5,$3
lw $4,0($0)
or $6,$4,$3
sw $4,12($0)
xori $4,$4,16113
lb $3,7($0)
xori $4,$4,34061
nor $4,$2,$3
lbu $1,5($0)
slt $3,$1,$3
xori $5,$2,51804
lhu $1,0($0)
subu $5,$4,$3
|
;3 - 5 + 7 - 9 + 11
;using even odd
mov bx,11
mov cx,5
mov si,0
mov di,2
Series:
mov ax,cx
div di
cmp dx,0
je cx_even
jne cx_odd
cx_even:
sub si,bx
sub bx,2
jmp exit
cx_odd:
add si,bx
sub bx,2
exit:
loop series
|
[bits 32]
; declare the main symbol will be referenced at linking time
[extern main]
; invoke the c function called main
call main
jmp $
|
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <cmath>
#include <climits>
#include <math.h>
#define X first
#define Y second
#define vsort(v) sort(v.begin(), v.end())
#define vrev(v) reverse(v.begin(), v.end())
#define P pair
// stoi(s): string to int
// stod(s): string to double
// INT_MAX
// INT_MIN
// LLONG_MAX
// LLONG_MIN
// DBL_MIN
// DBL_MAX
// LDBL_MIN
// LDBL_MAX
// A-Z: 65~90
// a-z: 97~122
// |a-z| = 26
using namespace std;
using ll = long long;
int main(int argc, const char *argv[])
{
char c;
cin >> c;
switch (c)
{
case 'A':
cout << 'T' << endl;
break;
case 'C':
cout << 'G' << endl;
break;
case 'G':
cout << 'C' << endl;
break;
case 'T':
cout << 'A' << endl;
break;
}
}
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/atom_api_web_contents.h"
#include "atom/browser/atom_browser_context.h"
#include "atom/common/api/api_messages.h"
#include "atom/common/native_mate_converters/gfx_converter.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "base/strings/utf_string_conversions.h"
#include "brightray/browser/inspectable_web_contents.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/resource_request_details.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/web_contents.h"
#include "native_mate/dictionary.h"
#include "native_mate/object_template_builder.h"
#include "atom/common/node_includes.h"
namespace atom {
namespace api {
namespace {
v8::Persistent<v8::ObjectTemplate> template_;
} // namespace
WebContents::WebContents(content::WebContents* web_contents)
: content::WebContentsObserver(web_contents),
guest_instance_id_(-1),
guest_opaque_(true),
auto_size_enabled_(false) {
}
WebContents::WebContents(const mate::Dictionary& options)
: guest_instance_id_(-1),
guest_opaque_(true),
auto_size_enabled_(false) {
options.Get("guestInstanceId", &guest_instance_id_);
auto browser_context = AtomBrowserContext::Get();
content::SiteInstance* site_instance = content::SiteInstance::CreateForURL(
browser_context, GURL("chrome-guest://fake-host"));
content::WebContents::CreateParams params(browser_context, site_instance);
bool is_guest;
if (options.Get("isGuest", &is_guest) && is_guest)
params.guest_delegate = this;
storage_.reset(brightray::InspectableWebContents::Create(params));
Observe(storage_->GetWebContents());
web_contents()->SetDelegate(this);
}
WebContents::~WebContents() {
Destroy();
}
bool WebContents::AddMessageToConsole(content::WebContents* source,
int32 level,
const base::string16& message,
int32 line_no,
const base::string16& source_id) {
base::ListValue args;
args.AppendInteger(level);
args.AppendString(message);
args.AppendInteger(line_no);
args.AppendString(source_id);
Emit("console-message", args);
return true;
}
bool WebContents::ShouldCreateWebContents(
content::WebContents* web_contents,
int route_id,
WindowContainerType window_container_type,
const base::string16& frame_name,
const GURL& target_url,
const std::string& partition_id,
content::SessionStorageNamespace* session_storage_namespace) {
base::ListValue args;
args.AppendString(target_url.spec());
args.AppendString(frame_name);
Emit("new-window", args);
return false;
}
void WebContents::CloseContents(content::WebContents* source) {
Emit("close");
}
content::WebContents* WebContents::OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) {
if (params.disposition != CURRENT_TAB)
return NULL;
content::NavigationController::LoadURLParams load_url_params(params.url);
load_url_params.referrer = params.referrer;
load_url_params.transition_type = params.transition;
load_url_params.extra_headers = params.extra_headers;
load_url_params.should_replace_current_entry =
params.should_replace_current_entry;
load_url_params.is_renderer_initiated = params.is_renderer_initiated;
load_url_params.transferred_global_request_id =
params.transferred_global_request_id;
web_contents()->GetController().LoadURLWithParams(load_url_params);
return web_contents();
}
void WebContents::HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (!attached())
return;
// Send the unhandled keyboard events back to the embedder to reprocess them.
embedder_web_contents_->GetDelegate()->HandleKeyboardEvent(
web_contents(), event);
}
void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) {
base::ListValue args;
args.AppendInteger(render_view_host->GetProcess()->GetID());
args.AppendInteger(render_view_host->GetRoutingID());
Emit("render-view-deleted", args);
}
void WebContents::RenderProcessGone(base::TerminationStatus status) {
Emit("crashed");
}
void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url) {
bool is_main_frame = !render_frame_host->GetParent();
base::ListValue args;
args.AppendBoolean(is_main_frame);
Emit("did-frame-finish-load", args);
if (is_main_frame)
Emit("did-finish-load");
}
void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url,
int error_code,
const base::string16& error_description) {
base::ListValue args;
args.AppendInteger(error_code);
args.AppendString(error_description);
Emit("did-fail-load", args);
}
void WebContents::DidStartLoading(content::RenderViewHost* render_view_host) {
Emit("did-start-loading");
}
void WebContents::DidStopLoading(content::RenderViewHost* render_view_host) {
Emit("did-stop-loading");
}
void WebContents::DidGetRedirectForResourceRequest(
content::RenderViewHost* render_view_host,
const content::ResourceRedirectDetails& details) {
base::ListValue args;
args.AppendString(details.url.spec());
args.AppendString(details.new_url.spec());
args.AppendBoolean(
details.resource_type == content::RESOURCE_TYPE_MAIN_FRAME);
Emit("did-get-redirect-request", args);
}
bool WebContents::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(WebContents, message)
IPC_MESSAGE_HANDLER(AtomViewHostMsg_Message, OnRendererMessage)
IPC_MESSAGE_HANDLER_DELAY_REPLY(AtomViewHostMsg_Message_Sync,
OnRendererMessageSync)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void WebContents::RenderViewReady() {
if (!is_guest())
return;
// We don't want to accidentally set the opacity of an interstitial page.
// WebContents::GetRenderWidgetHostView will return the RWHV of an
// interstitial page if one is showing at this time. We only want opacity
// to apply to web pages.
web_contents()->GetRenderViewHost()->GetView()->
SetBackgroundOpaque(guest_opaque_);
content::RenderViewHost* rvh = web_contents()->GetRenderViewHost();
if (auto_size_enabled_) {
rvh->EnableAutoResize(min_auto_size_, max_auto_size_);
} else {
rvh->DisableAutoResize(element_size_);
}
}
void WebContents::WebContentsDestroyed() {
// The RenderViewDeleted was not called when the WebContents is destroyed.
RenderViewDeleted(web_contents()->GetRenderViewHost());
Emit("destroyed");
}
void WebContents::WillAttach(content::WebContents* embedder_web_contents,
const base::DictionaryValue& extra_params) {
embedder_web_contents_ = embedder_web_contents;
extra_params_.reset(extra_params.DeepCopy());
}
content::WebContents* WebContents::CreateNewGuestWindow(
const content::WebContents::CreateParams& create_params) {
NOTREACHED() << "Should not create new window from guest";
return nullptr;
}
void WebContents::DidAttach() {
base::ListValue args;
args.Append(extra_params_.release());
Emit("did-attach", args);
}
int WebContents::GetGuestInstanceID() const {
return guest_instance_id_;
}
void WebContents::ElementSizeChanged(const gfx::Size& old_size,
const gfx::Size& new_size) {
element_size_ = new_size;
}
void WebContents::GuestSizeChanged(const gfx::Size& old_size,
const gfx::Size& new_size) {
if (!auto_size_enabled_)
return;
guest_size_ = new_size;
GuestSizeChangedDueToAutoSize(old_size, new_size);
}
void WebContents::RequestPointerLockPermission(
bool user_gesture,
bool last_unlocked_by_target,
const base::Callback<void(bool enabled)>& callback) {
callback.Run(true);
}
void WebContents::RegisterDestructionCallback(
const DestructionCallback& callback) {
destruction_callback_ = callback;
}
void WebContents::Destroy() {
if (storage_) {
if (!destruction_callback_.is_null())
destruction_callback_.Run();
Observe(nullptr);
storage_.reset();
}
}
bool WebContents::IsAlive() const {
return web_contents() != NULL;
}
void WebContents::LoadURL(const GURL& url) {
content::NavigationController::LoadURLParams params(url);
params.transition_type = content::PAGE_TRANSITION_TYPED;
params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
web_contents()->GetController().LoadURLWithParams(params);
}
GURL WebContents::GetURL() const {
return web_contents()->GetURL();
}
base::string16 WebContents::GetTitle() const {
return web_contents()->GetTitle();
}
bool WebContents::IsLoading() const {
return web_contents()->IsLoading();
}
bool WebContents::IsWaitingForResponse() const {
return web_contents()->IsWaitingForResponse();
}
void WebContents::Stop() {
web_contents()->Stop();
}
void WebContents::Reload() {
// Navigating to a URL would always restart the renderer process, we want this
// because normal reloading will break our node integration.
// This is done by AtomBrowserClient::ShouldSwapProcessesForNavigation.
LoadURL(GetURL());
}
void WebContents::ReloadIgnoringCache() {
Reload();
}
bool WebContents::CanGoBack() const {
return web_contents()->GetController().CanGoBack();
}
bool WebContents::CanGoForward() const {
return web_contents()->GetController().CanGoForward();
}
bool WebContents::CanGoToOffset(int offset) const {
return web_contents()->GetController().CanGoToOffset(offset);
}
void WebContents::GoBack() {
web_contents()->GetController().GoBack();
}
void WebContents::GoForward() {
web_contents()->GetController().GoForward();
}
void WebContents::GoToIndex(int index) {
web_contents()->GetController().GoToIndex(index);
}
void WebContents::GoToOffset(int offset) {
web_contents()->GetController().GoToOffset(offset);
}
int WebContents::GetRoutingID() const {
return web_contents()->GetRoutingID();
}
int WebContents::GetProcessID() const {
return web_contents()->GetRenderProcessHost()->GetID();
}
bool WebContents::IsCrashed() const {
return web_contents()->IsCrashed();
}
void WebContents::SetUserAgent(const std::string& user_agent) {
web_contents()->SetUserAgentOverride(user_agent);
}
void WebContents::InsertCSS(const std::string& css) {
web_contents()->InsertCSS(css);
}
void WebContents::ExecuteJavaScript(const base::string16& code) {
web_contents()->GetMainFrame()->ExecuteJavaScript(code);
}
void WebContents::OpenDevTools() {
storage_->SetCanDock(false);
storage_->ShowDevTools();
}
void WebContents::CloseDevTools() {
storage_->CloseDevTools();
}
bool WebContents::IsDevToolsOpened() {
return storage_->IsDevToolsViewShowing();
}
bool WebContents::SendIPCMessage(const base::string16& channel,
const base::ListValue& args) {
return Send(new AtomViewMsg_Message(routing_id(), channel, args));
}
void WebContents::SetAutoSize(bool enabled,
const gfx::Size& min_size,
const gfx::Size& max_size) {
min_auto_size_ = min_size;
min_auto_size_.SetToMin(max_size);
max_auto_size_ = max_size;
max_auto_size_.SetToMax(min_size);
enabled &= !min_auto_size_.IsEmpty() && !max_auto_size_.IsEmpty();
if (!enabled && !auto_size_enabled_)
return;
auto_size_enabled_ = enabled;
if (!attached())
return;
content::RenderViewHost* rvh = web_contents()->GetRenderViewHost();
if (auto_size_enabled_) {
rvh->EnableAutoResize(min_auto_size_, max_auto_size_);
} else {
rvh->DisableAutoResize(element_size_);
guest_size_ = element_size_;
GuestSizeChangedDueToAutoSize(guest_size_, element_size_);
}
}
void WebContents::SetAllowTransparency(bool allow) {
if (guest_opaque_ != allow)
return;
guest_opaque_ = !allow;
if (!web_contents()->GetRenderViewHost()->GetView())
return;
web_contents()->GetRenderViewHost()->GetView()->SetBackgroundOpaque(!allow);
}
mate::ObjectTemplateBuilder WebContents::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
if (template_.IsEmpty())
template_.Reset(isolate, mate::ObjectTemplateBuilder(isolate)
.SetMethod("destroy", &WebContents::Destroy)
.SetMethod("isAlive", &WebContents::IsAlive)
.SetMethod("loadUrl", &WebContents::LoadURL)
.SetMethod("getUrl", &WebContents::GetURL)
.SetMethod("getTitle", &WebContents::GetTitle)
.SetMethod("isLoading", &WebContents::IsLoading)
.SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
.SetMethod("stop", &WebContents::Stop)
.SetMethod("reload", &WebContents::Reload)
.SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache)
.SetMethod("canGoBack", &WebContents::CanGoBack)
.SetMethod("canGoForward", &WebContents::CanGoForward)
.SetMethod("canGoToOffset", &WebContents::CanGoToOffset)
.SetMethod("goBack", &WebContents::GoBack)
.SetMethod("goForward", &WebContents::GoForward)
.SetMethod("goToIndex", &WebContents::GoToIndex)
.SetMethod("goToOffset", &WebContents::GoToOffset)
.SetMethod("getRoutingId", &WebContents::GetRoutingID)
.SetMethod("getProcessId", &WebContents::GetProcessID)
.SetMethod("isCrashed", &WebContents::IsCrashed)
.SetMethod("setUserAgent", &WebContents::SetUserAgent)
.SetMethod("insertCSS", &WebContents::InsertCSS)
.SetMethod("_executeJavaScript", &WebContents::ExecuteJavaScript)
.SetMethod("_send", &WebContents::SendIPCMessage)
.SetMethod("setAutoSize", &WebContents::SetAutoSize)
.SetMethod("setAllowTransparency", &WebContents::SetAllowTransparency)
.SetMethod("isGuest", &WebContents::is_guest)
.SetMethod("openDevTools", &WebContents::OpenDevTools)
.SetMethod("closeDevTools", &WebContents::CloseDevTools)
.SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
.Build());
return mate::ObjectTemplateBuilder(
isolate, v8::Local<v8::ObjectTemplate>::New(isolate, template_));
}
void WebContents::OnRendererMessage(const base::string16& channel,
const base::ListValue& args) {
// webContents.emit(channel, new Event(), args...);
Emit(base::UTF16ToUTF8(channel), args);
}
void WebContents::OnRendererMessageSync(const base::string16& channel,
const base::ListValue& args,
IPC::Message* message) {
// webContents.emit(channel, new Event(sender, message), args...);
Emit(base::UTF16ToUTF8(channel), args, web_contents(), message);
}
void WebContents::GuestSizeChangedDueToAutoSize(const gfx::Size& old_size,
const gfx::Size& new_size) {
base::ListValue args;
args.AppendInteger(old_size.width());
args.AppendInteger(old_size.height());
args.AppendInteger(new_size.width());
args.AppendInteger(new_size.height());
Emit("size-changed", args);
}
// static
mate::Handle<WebContents> WebContents::CreateFrom(
v8::Isolate* isolate, content::WebContents* web_contents) {
return mate::CreateHandle(isolate, new WebContents(web_contents));
}
// static
mate::Handle<WebContents> WebContents::Create(
v8::Isolate* isolate, const mate::Dictionary& options) {
return mate::CreateHandle(isolate, new WebContents(options));
}
} // namespace api
} // namespace atom
namespace {
void Initialize(v8::Handle<v8::Object> exports, v8::Handle<v8::Value> unused,
v8::Handle<v8::Context> context, void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.SetMethod("create", &atom::api::WebContents::Create);
}
} // namespace
NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_web_contents, Initialize)
|
; double nan(const char *tagp)
SECTION code_fp_math48
PUBLIC am48_nan
EXTERN am48_derror_einval_zc
; return nan
;
; enter : hl = char *tagp
;
; exit : AC' = 0
; carry set, errno set
;
; note : math48 does not support nan
;
; uses : af, bc', de', hl'
defc am48_nan = am48_derror_einval_zc
|
// Copyright (c) 2018-2019 AccelByte Inc. All Rights Reserved.
// This is licensed software from AccelByte Inc, for limitations
// and restrictions contact your company contract manager.
#include "Blueprints/AccelByteWalletBlueprints.h"
#include "Core/AccelByteSettings.h"
#include "Api/AccelByteWalletApi.h"
#include "Core/AccelByteCredentials.h"
#include "Core/AccelByteRegistry.h"
using AccelByte::Api::Wallet;
using AccelByte::FErrorHandler;
using AccelByte::THandler;
using AccelByte::Settings;
using AccelByte::Credentials;
void UAccelByteBlueprintsWallet::GetWalletInfoByCurrencyCode(const FString& CurrencyCode, const FGetWalletByCurrencyCodeSuccess& OnSuccess, const FBlueprintErrorHandler& OnError)
{
FRegistry::Wallet.GetWalletInfoByCurrencyCode(CurrencyCode, THandler<FAccelByteModelsWalletInfo>::CreateLambda([OnSuccess](const FAccelByteModelsWalletInfo& Result)
{
OnSuccess.ExecuteIfBound(Result);
}), FErrorHandler::CreateLambda([OnError](int32 ErrorCode, const FString& ErrorMessage)
{
OnError.ExecuteIfBound(ErrorCode, ErrorMessage);
}));
}
|
.size 8000
.text@48
jp lstatint
.text@100
jp lbegin
.data@143
c0
.text@150
lbegin:
ld a, 00
ldff(ff), a
ld a, 30
ldff(00), a
ld a, 01
ldff(4d), a
stop, 00
ld a, ff
ldff(45), a
ld b, 91
call lwaitly_b
ld hl, fe00
ld d, 10
ld a, d
ld(hl++), a
ld a, 08
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 0d
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 12
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 28
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 2d
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 32
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 48
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 4d
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 52
ld(hl++), a
ld a, 40
ldff(41), a
ld a, 02
ldff(ff), a
xor a, a
ldff(0f), a
ei
ld a, 01
ldff(45), a
ld c, 41
ld a, 93
ldff(40), a
ld a, 07
ldff(43), a
.text@1000
lstatint:
nop
.text@109a
ldff a, (c)
and a, 03
jp lprint_a
.text@7000
lprint_a:
push af
ld b, 91
call lwaitly_b
xor a, a
ldff(40), a
pop af
ld(9800), a
ld bc, 7a00
ld hl, 8000
ld d, a0
lprint_copytiles:
ld a, (bc)
inc bc
ld(hl++), a
dec d
jrnz lprint_copytiles
ld a, c0
ldff(47), a
ld a, 80
ldff(68), a
ld a, ff
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
xor a, a
ldff(69), a
ldff(69), a
ldff(43), a
ld a, 91
ldff(40), a
lprint_limbo:
jr lprint_limbo
.text@7400
lwaitly_b:
ld c, 44
lwaitly_b_loop:
ldff a, (c)
cmp a, b
jrnz lwaitly_b_loop
ret
.data@7a00
00 00 7f 7f 41 41 41 41
41 41 41 41 41 41 7f 7f
00 00 08 08 08 08 08 08
08 08 08 08 08 08 08 08
00 00 7f 7f 01 01 01 01
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 01 01 01 01
3f 3f 01 01 01 01 7f 7f
00 00 41 41 41 41 41 41
7f 7f 01 01 01 01 01 01
00 00 7f 7f 40 40 40 40
7e 7e 01 01 01 01 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 41 41 41 41 7f 7f
00 00 7f 7f 01 01 02 02
04 04 08 08 10 10 10 10
00 00 3e 3e 41 41 41 41
3e 3e 41 41 41 41 3e 3e
00 00 7f 7f 41 41 41 41
7f 7f 01 01 01 01 7f 7f
|
; A253213: a(n) = 10^n + 9.
; 10,19,109,1009,10009,100009,1000009,10000009,100000009,1000000009,10000000009,100000000009,1000000000009,10000000000009,100000000000009,1000000000000009,10000000000000009,100000000000000009,1000000000000000009,10000000000000000009
mov $1,10
pow $1,$0
add $1,9
mov $0,$1
|
; all of these should be legal and should just result in the offset portion
foo equ 1:2
jmp far[foo] ; out: ff 2e 02 00
mov ax,[foo] ; out: a1 02 00
push dword [foo] ; out: 66 ff 36 02 00
mov ax,foo ; out: b8 02 00
|
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/redshift/model/HsmConfiguration.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::Utils::Xml;
using namespace Aws::Utils;
namespace Aws
{
namespace Redshift
{
namespace Model
{
HsmConfiguration::HsmConfiguration() :
m_hsmConfigurationIdentifierHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_hsmIpAddressHasBeenSet(false),
m_hsmPartitionNameHasBeenSet(false),
m_tagsHasBeenSet(false)
{
}
HsmConfiguration::HsmConfiguration(const XmlNode& xmlNode) :
m_hsmConfigurationIdentifierHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_hsmIpAddressHasBeenSet(false),
m_hsmPartitionNameHasBeenSet(false),
m_tagsHasBeenSet(false)
{
*this = xmlNode;
}
HsmConfiguration& HsmConfiguration::operator =(const XmlNode& xmlNode)
{
XmlNode resultNode = xmlNode;
if(!resultNode.IsNull())
{
XmlNode hsmConfigurationIdentifierNode = resultNode.FirstChild("HsmConfigurationIdentifier");
if(!hsmConfigurationIdentifierNode.IsNull())
{
m_hsmConfigurationIdentifier = StringUtils::Trim(hsmConfigurationIdentifierNode.GetText().c_str());
m_hsmConfigurationIdentifierHasBeenSet = true;
}
XmlNode descriptionNode = resultNode.FirstChild("Description");
if(!descriptionNode.IsNull())
{
m_description = StringUtils::Trim(descriptionNode.GetText().c_str());
m_descriptionHasBeenSet = true;
}
XmlNode hsmIpAddressNode = resultNode.FirstChild("HsmIpAddress");
if(!hsmIpAddressNode.IsNull())
{
m_hsmIpAddress = StringUtils::Trim(hsmIpAddressNode.GetText().c_str());
m_hsmIpAddressHasBeenSet = true;
}
XmlNode hsmPartitionNameNode = resultNode.FirstChild("HsmPartitionName");
if(!hsmPartitionNameNode.IsNull())
{
m_hsmPartitionName = StringUtils::Trim(hsmPartitionNameNode.GetText().c_str());
m_hsmPartitionNameHasBeenSet = true;
}
XmlNode tagsNode = resultNode.FirstChild("Tags");
if(!tagsNode.IsNull())
{
XmlNode tagsMember = tagsNode.FirstChild("Tag");
while(!tagsMember.IsNull())
{
m_tags.push_back(tagsMember);
tagsMember = tagsMember.NextNode("Tag");
}
m_tagsHasBeenSet = true;
}
}
return *this;
}
void HsmConfiguration::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const
{
if(m_hsmConfigurationIdentifierHasBeenSet)
{
oStream << location << index << locationValue << ".HsmConfigurationIdentifier=" << StringUtils::URLEncode(m_hsmConfigurationIdentifier.c_str()) << "&";
}
if(m_descriptionHasBeenSet)
{
oStream << location << index << locationValue << ".Description=" << StringUtils::URLEncode(m_description.c_str()) << "&";
}
if(m_hsmIpAddressHasBeenSet)
{
oStream << location << index << locationValue << ".HsmIpAddress=" << StringUtils::URLEncode(m_hsmIpAddress.c_str()) << "&";
}
if(m_hsmPartitionNameHasBeenSet)
{
oStream << location << index << locationValue << ".HsmPartitionName=" << StringUtils::URLEncode(m_hsmPartitionName.c_str()) << "&";
}
if(m_tagsHasBeenSet)
{
unsigned tagsIdx = 1;
for(auto& item : m_tags)
{
Aws::StringStream tagsSs;
tagsSs << location << index << locationValue << ".Tag." << tagsIdx++;
item.OutputToStream(oStream, tagsSs.str().c_str());
}
}
}
void HsmConfiguration::OutputToStream(Aws::OStream& oStream, const char* location) const
{
if(m_hsmConfigurationIdentifierHasBeenSet)
{
oStream << location << ".HsmConfigurationIdentifier=" << StringUtils::URLEncode(m_hsmConfigurationIdentifier.c_str()) << "&";
}
if(m_descriptionHasBeenSet)
{
oStream << location << ".Description=" << StringUtils::URLEncode(m_description.c_str()) << "&";
}
if(m_hsmIpAddressHasBeenSet)
{
oStream << location << ".HsmIpAddress=" << StringUtils::URLEncode(m_hsmIpAddress.c_str()) << "&";
}
if(m_hsmPartitionNameHasBeenSet)
{
oStream << location << ".HsmPartitionName=" << StringUtils::URLEncode(m_hsmPartitionName.c_str()) << "&";
}
if(m_tagsHasBeenSet)
{
unsigned tagsIdx = 1;
for(auto& item : m_tags)
{
Aws::StringStream tagsSs;
tagsSs << location << ".Tag." << tagsIdx++;
item.OutputToStream(oStream, tagsSs.str().c_str());
}
}
}
} // namespace Model
} // namespace Redshift
} // namespace Aws
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.